---
title: "How to be gracious about political loss – The importance of good loser messages in policy controversies"
subtitle: Online Appendix
output:
  html_document:
    toc: true
    toc_depth: 3
    number_sections: true
    self_contained: yes
bibliography: book.bib      
always_allow_html: yes
knit: pagedown::chrome_print
---

\newpage
# Preface
This is the Supplementary Material for the manuscript entitled *How to be civil about political loss 
– The importance of good loser messages*. 
by Peter Esaiasson, Sveinung Arnesen, and Hannah Werner.

We pre-registered [Study 2](http://aspredicted.org/blind.php?x=a84rk7), and [Study 3](http://aspredicted.org/blind.php?x=t4ss9j/).
Study 3 was preregistered after the data had been collected by the fieldwork agency (sub-contractor), but before the researchers had received the data.
These studies were subject to ethics review by the steering committee of the Norwegian Citizen Panel through which the survey embedded experiments were fielded.  
The Norwegian Citizen Panel operates under GDPR compliance, as evaluated by the NSD -- Norwegian Centre for Research Data in a Data Protection Impact Assessment that privacy concerns are maintained appropriately at the NCP (project number 118868 at NSD).
The Swedish study (Study 1) was reviewed by The Regional Ethics Review Board in Umeå as part of the Swedish leg of the European Values Survey (#2017-221-31).

When not otherwise stated, we followed the pre-registration. 

We deviated from it in the following ways: 

1.	Exclusion criteria. 
While we registered to exclude individuals that raced through the survey in Study 2, we have since then learned that exclusion based on such a post-treatment variable can bias the obtained effects (Montgomery et al, 2018). 
Accordingly, we present the analysis on the full sample in the main text. 
The analysis using the reduced sample can be found in this Appendix). 

2.	For study 2, we pre-registered a hypothesis that predicts an interaction between the good loser norm and the good loser message.
Since there is little variance on the good-loser norm variable, this analysis is less insightful than we had anticipated. 
We therefore do not present this analysis in the main text but in the Appendix. 

3.	For study 3, we pre-registered that we would use two indicators of fairness perceptions. 
To keep the dependent variable comparable across studies we have later on decided to only present the analysis with the item:
'How fair was the decision-making procedure?' for all three studies. 
The analysis using the additional item 'How reasonable do you think the decision was?' is included in the robustness check analysis in the paper (Table 2). 

4.	For study 3, we missed to specify that there are two good loser message like in study 2 (for which we have the same expectations):
A generic and a specific good loser message.

5.	While we use the wording good loser prime in the pre-registration, we have later decided to use good loser message in the manuscript.

\newpage
## Acknowledgements
Previous versions of the paper were presented at the 2018 and 2019 Midwest meetings, at the 4th Barcelona-Gothenburg-Bergen Workshop on Experimental Political Science, and at Department of Political Science Research Seminar at University of Vienna. 
We thank participants and in particular Elisabeth Ivarsflaten and Mike Tomz for constructive suggestions.

We want to acknowledge fundings from the Research Council of Norway (Grants #262986 and #295892), and from the Swedish Research Council (Grant # 2017-01146).

```{r setup, include=FALSE}
# automatically create a bib database for R packages
knitr::write_bib(c(
  .packages(), 'bookdown', 'knitr', 'rmarkdown'
), 'packages.bib')

#load packages
if(!require("broom")){install.packages("broom");  library(broom)}
if(!require("devtools")){install.packages("devtools");  library(devtools)}
if(!require("estimatr")){install.packages("estimatr"); library(estimatr)}
if(!require("haven")){install.packages("haven");  library(haven)}
if(!require("here")){install.packages("here");  library(here)}
if(!require("knitr")){install.packages("knitr");  library(knitr)}
options(kableExtra.latex.load_packages = FALSE) 
if(!require("kableExtra")){install.packages("kableExtra");  library(kableExtra)}
if(!require("margins")){install.packages("margins");  library(margins)}
if(!require("naniar")){install.packages("naniar");  library(naniar)}
if(!require("openxlsx")){install.packages("openxlsx");  library(openxlsx)}
if(!require("patchwork")){install.packages("patchwork");  library(patchwork)}
if(!require("rio")){install.packages("rio");  library(rio)}
if(!require("tidyverse")){install.packages("tidyverse");  library(tidyverse)}
if(!require("remotes")){install.packages("remotes");  library(remotes)}
## Utils. 
#source("goodloser-utils.R")
remotes::install_github("leeper/cregg")

#set global R Markdown options
options(tinytex.verbose = TRUE)
knitr::opts_chunk$set(echo = FALSE, knitr.kable.NA = "", warning = FALSE, message = FALSE)

#set seed
set.seed(2016)
```



\newpage
# STUDY I {}

The experiment for Study I was fielded in Sweden in the fall of 2017 and spring of 2018 as an add-on to the fifth wave of the European Values Survey (EVS, PI Susanne Wallman Lundåsen). EVS is based on a probability sample of the Swedish population age 18 or older (n = 1194). Interviews were face-to-face. The fieldwork organization was IPSOS, Sweden. For a detailed documentation we refer to https://europeanvaluesstudy.eu/methodology-data-documentation/. Study 1 was one of three experiments included in a paper and pencil leave behind. The return rate of the questionnaire was 85% (n =1019).

```{r 1010_import, eval=FALSE}
scp_raw <- import("Data/Studie3_Esaiasson_20180611.sav") %>% 
  mutate(idnummer = as.numeric(idnummer))

d <- scp_raw %>%
  select("age" = "Q64",
          "gender" = "Q63",
         "education" = "Q81",
         "polint" = "Q29",
         "leftright" = "Q31",
          "opinion_ban" = "S3_1_1",
          "opinion_strength" = "S3_2_1",
          "fairness_1" = "S3_4_1_1",
          "fairness_2" = "S3_4_1_2",
          "justice" = "S3_5_1", #Note: There was only variable with this question item
          "eval_1" = "S3_6_1_1",
          "eval_2" = "S3_6_1_2",
          "accept_1" = "S3_7_1_1",
          "accept_2" = "S3_7_1_2",
          "comply_1" = "S3_8_1_1",
          "comply_2" = "S3_8_1_2",
          "treatment" = "Studie3sel"
                  ) 
```

```{r 1011_prepare, eval=FALSE}

#Restructure data so that post measures of treatment and control groups are in the same variable
d <- d %>%
  pivot_longer(fairness_1:fairness_2, names_to = 'fairness_ran', values_to = 'fairness', values_drop_na = TRUE)%>%
  pivot_longer(eval_1:eval_2, names_to = 'eval_ran', values_to = 'eval', values_drop_na = TRUE) %>% 
  pivot_longer(accept_1:accept_2, names_to = 'accept_ran', values_to = 'accept', values_drop_na = TRUE) %>% 
  pivot_longer(comply_1:comply_2, names_to = 'comply_ran', values_to = 'comply', values_drop_na = TRUE) 

##New variables, recode, and label
d <-  d %>% mutate(leftright = na_if(leftright, '_na_'),
                    leftright = na_if(leftright, '_dk_'),
                   leftright = as.numeric(leftright),
                   polint = na_if(polint, '_na_'),
                   polint = na_if(polint, '_dk_'),
                   polint = -(polint)+5, #Reverse scale 
                   favorability = case_when(
                     treatment %in% 1:3 & opinion_ban == 1 ~ "Unfavorable", #Outcome favorability
                     treatment %in% 1:3 & opinion_ban == 2 ~ "Favorable",
                     treatment %in% 4:6 & opinion_ban == 2 ~ "Unfavorable",
                     treatment %in% 4:6 & opinion_ban == 1 ~ "Favorable"),
                   treatment = case_when(
                     .[["treatment"]] == 1 | .[["treatment"]] == 4 ~ "Lamenting politician", #Label values on treatment variable
                     .[["treatment"]] == 2 | .[["treatment"]] == 5 ~ "General prime",
                     .[["treatment"]] == 3 | .[["treatment"]] == 6 ~ "Not shown"),
                   treatment = lvls_reorder(treatment, c(3, 2 , 1)), # Reorder treatment levels
                   opinion_ban = case_when( #Label values on opinion ban variable
                     .[["opinion_ban"]] == 1 ~ "Anti",
                     .[["opinion_ban"]] == 2 ~ "Pro"),
                   education = case_when(education %in% 1:8 ~ 0,
                                         education %in% 9:19 ~ 1)
)


export(d, here("Data", 'Goodloser-exp1.rds'))
```

```{r 1012_reload}
d <- import(here("Data", 'Goodloser-exp1.rds'))
```

\newpage
## Pre-treatment measures

### Ban on begging - opinion
```{r 1020_pre_begging}

d %>% group_by(opinion_ban) %>%
   summarize(N_obs = n()) %>% 
  mutate(Percent_obs = round(N_obs/(sum(N_obs))*100),
         opinion_ban = case_when(opinion_ban == 'Anti' ~ 'Against ban',
                                 opinion_ban == 'Pro' ~ 'For ban')) %>%
  ungroup() %>% 
  kable(booktabs = TRUE, linesep = "", escape = F, caption = "What is your opinion on a ban on begging in your municipality?", col.names = linebreak(c("Value", "N", "Percent"))) %>% 
  kable_styling(latex_options = "HOLD_position")

#save to file
d %>% group_by(opinion_ban) %>%
   summarize(N_obs = n()) %>% 
  mutate(Percent_obs = round(N_obs/(sum(N_obs))*100),
         opinion_ban = case_when(opinion_ban == 'Anti' ~ 'Against ban',
                                 opinion_ban == 'Pro' ~ 'For ban')) %>%
  ungroup() %>% 
  kable(booktabs = TRUE, linesep = "", escape = F, caption = "What is your opinion on a ban on begging in your municipality?", col.names = linebreak(c("Value", "N", "Percent"))) %>% 
  kable_styling(latex_options = "HOLD_position")%>% 
  cat(., file = here("output", "swevig", "tbls", "html", "tbl-begging-pref-swevig.html"))
```

### Ban on begging - importance
```{r 1021_pre_begging2}
d %>% mutate(
     opinion_strength = case_when(
      opinion_strength == 1 ~ "1 Not important at all",
      opinion_strength == 2 ~ "2",
      opinion_strength == 3 ~ "3",
      opinion_strength == 4 ~ "4",
      opinion_strength == 5 ~ "5",
      opinion_strength == 6 ~ "6",
      opinion_strength == 7 ~ "7 Very important")) %>% 
  group_by(opinion_strength) %>%
   summarize(N_obs = n()) %>% 
  mutate(Percent_obs = round(N_obs/(sum(N_obs))*100)) %>%
    ungroup() %>% 
  kable(booktabs = TRUE, linesep = "", escape = F, caption = "How important is the issue of ban on begging to you personally?", col.names = linebreak(c("Value", "N", "Percent"))) %>% 
  footnote(footnote_as_chunk = ) %>% 
  kable_styling(latex_options = "HOLD_position")

#save to file
d %>% mutate(
     opinion_strength = case_when(
      opinion_strength == 1 ~ "1 Not important at all",
      opinion_strength == 2 ~ "2",
      opinion_strength == 3 ~ "3",
      opinion_strength == 4 ~ "4",
      opinion_strength == 5 ~ "5",
      opinion_strength == 6 ~ "6",
      opinion_strength == 7 ~ "7 Very important")) %>% 
  group_by(opinion_strength) %>%
   summarize(N_obs = n()) %>% 
  mutate(Percent_obs = round(N_obs/(sum(N_obs))*100)) %>%
  ungroup() %>% 
  kable(booktabs = TRUE, linesep = "", escape = F, caption = "How important is the issue of ban on begging to you personally?", col.names = linebreak(c("Value", "N", "Percent"))) %>% 
  kable_styling(latex_options = "HOLD_position")%>% 
  cat(., file = here("output", "swevig", "tbls", "html", "tbl-begging-importance-swevig.html"))
```
The mean score for the pre treatment measure "How important is the issue of ban on begging to you personally?" is `r round(mean(d$opinion_strength), digits=2)`, and the standard deviation is `r round(sd(d$opinion_strength), digits=2)`.

\newpage
## Experimental vignette

*Experimental vignette.*

>Imagine that your municipality is about to decide whether begging on the streets should be banned or allowed within the municipal borders. The decision can be made in different ways: One option is that the local political representatives make the decision. Another option is that the citizens of the municipality decide through a referendum. Please image how you would react if this scenario occurred in your municipality: After a debate in the media, the local political representatives decide to ban begging in the municipality. *Treatment text follows.*

```{r 1031_vignette}
table <- tibble(Treatment = c("No prime", "Lamenting politician", "Generic good loser prime"), Text = c("Imagine that your municipality is about to decide whether begging on the streets should be banned or allowed within the municipal borders. The decision can be made in different ways: One option is that the local political representatives make the decision. Another option is that the citizens of the municipality decide through a referendum. Please image how you would react if this scenario occurred in your municipality: After a debate in the media, the local political representatives decide to ban begging in the municipality.", 
                                                                                             "Imagine that your municipality is about to decide whether begging on the streets should be banned or allowed within the municipal borders. The decision can be made in different ways: One option is that the local political representatives make the decision. Another option is that the citizens of the municipality decide through a referendum. Please image how you would react if this scenario occurred in your municipality: After a debate in the media, the local political representatives decide to ban begging in the municipality. After the decision, the leader of one of the parties who where in favor of a ban states that they are disappointed and that the decision was wrong.",
                                                                                             "Imagine that your municipality is about to decide whether begging on the streets should be banned or allowed within the municipal borders. The decision can be made in different ways: One option is that the local political representatives make the decision. Another option is that the citizens of the municipality decide through a referendum. Please image how you would react if this scenario occurred in your municipality: After a debate in the media, the local political representatives decide to ban begging in the municipality. After the decision, the leader of one of the parties who where in favor of a ban states that they are disappointed and that the decision was wrong, but that's how it is like living in a democracy.")
                )%>% 
    mutate_all(linebreak)

kable(table, booktabs = T, linesep = "", escape = F,  caption = "Vignette treatments and texts, Swedish vignette experiment", col.names = linebreak(c("Treatment", "Text"))) %>% 
    collapse_rows(columns = 1, latex_hline = "major", valign = "top") %>% 
  kable_styling(latex_options = c("scale_down", "HOLD_position"))

#save to file
kable(table, booktabs = T, linesep = "", escape = F,  caption = "Vignette treatments and texts, Swedish vignette experiment", col.names = linebreak(c("Treatment", "Text"))) %>% 
    collapse_rows(columns = 1, latex_hline = "major", valign = "top") %>% 
  kable_styling(latex_options = c("scale_down", "HOLD_position"))%>% 
  cat(., file = here("output", "swevig", "tbls", "html", "tbl-vignette-swevig.html"))
```


### Descriptive information about treatment groups
```{r 1032_balance}
#Gender
fig1 <- d %>% mutate(gender = as.numeric(gender)-1) %>% 
  ggplot(aes(x = treatment, y = gender)) +
stat_summary(fun.data = mean_cl_normal, geom = 'linerange') +
  stat_summary(fun.data = mean_cl_normal, geom = 'point') +
  scale_y_continuous(limits = c(0,1),
                   breaks = seq(from = 0, to = 1, by = 0.2)) +
  labs(x = '',
       y = '',
       title = 'Gender',
       subtitle = 'Proportion Females') +
    coord_flip() +
  theme_bw()

#Save figure in png and pdf format
ggsave("exp1-balance-gender.png",
  plot = fig1,
  width = 7, height = 2.75
)

#Age
fig2 <- d %>% ggplot(aes(x = treatment, y = age)) +
stat_summary(fun.data = mean_cl_normal, geom = 'linerange') +
  stat_summary(fun.data = mean_cl_normal, geom = 'point') +
  scale_y_continuous(limits = c(18, 100),
                     breaks = seq(20, 100, by = 20)) +
  labs(x = '',
       y = '',
       title = 'Years of Age') +
    coord_flip() +
theme_bw() 

#Save figure in png and pdf format
ggsave("exp1-balance-age.png",
  plot = fig2,
  width = 7, height = 2.75
)

#Political interest
fig3 <- d %>% ggplot(aes(x = treatment, y = polint)) +
stat_summary(fun.data = mean_cl_normal, geom = 'linerange') +
  stat_summary(fun.data = mean_cl_normal, geom = 'point') +
  scale_y_continuous(limits = c(1,4),
                     breaks = 1:4,
                   labels = c('Not interested at all',
                              '',
                              '',
                              'Very interested')) +
  labs(x = '',
       y = '',
       title = "Political interest") +
  coord_flip() +
theme_bw() 

#Save figure in png and pdf format
ggsave("exp1-balance-polint.png",
  plot = fig3,
  width = 7, height = 2.75
)

patchwork <- (fig1 + fig2) / fig3
patchwork + plot_annotation(title = 'Descriptive information about treatment groups', 
                           caption = 'Error bars represent 95% confidence intervals.')
```

\newpage
## Post-treatment measures
### Fairness

```{r 1041_outcome_measures_fairness}

d %>% mutate(
  fairness = case_when(
      fairness == 1 ~ "1 Not fair at all",
      fairness == 2 ~ "2",
      fairness == 3 ~ "3",
      fairness == 4 ~ "4",
      fairness == 5 ~ "5",
      fairness == 6 ~ "6",
      fairness == 7 ~ "7 Very fair")) %>% 
  group_by(fairness) %>%
   summarize(N_obs = n()) %>% 
  mutate(Percent_obs = round(N_obs/(sum(N_obs))*100)) %>% 
  kable(booktabs = TRUE, linesep = "", escape = F, caption = "What do you think about the way the decision was made?", col.names = linebreak(c("Value", "N", "Percent")))%>% 
  kable_styling(latex_options = "HOLD_position")


d %>% mutate(
  fairness = case_when(
      fairness == 1 ~ "1 Not fair at all",
      fairness == 2 ~ "2",
      fairness == 3 ~ "3",
      fairness == 4 ~ "4",
      fairness == 5 ~ "5",
      fairness == 6 ~ "6",
      fairness == 7 ~ "7 Very fair")) %>% 
  group_by(fairness) %>%
   summarize(N_obs = n()) %>% 
  mutate(Percent_obs = round(N_obs/(sum(N_obs))*100)) %>% 
  kable(booktabs = TRUE, linesep = "", escape = F, caption = "What do you think about the way the decision was made?", col.names = linebreak(c("Value", "N", "Percent")))%>% 
  kable_styling(latex_options = "HOLD_position") %>% 
  cat(., file = here("output", "swevig", "tbls", "html", "tbl-dv-fairness-swevig.html"))
```
The mean score for the post treatment measure "What do you think about the way the decision was made?" is `r round(mean(d$fairness), digits=2)`, and the standard deviation is `r round(sd(d$fairness), digits=2)`.

### Acceptance

```{r 1041_outcome_measures_accept}

d %>% mutate(
  accept = case_when(
      accept == 1 ~ "1 Not willing at all",
      accept == 2 ~ "2",
      accept == 3 ~ "3",
      accept == 4 ~ "4",
      accept == 5 ~ "5",
      accept == 6 ~ "6",
      accept == 7 ~ "7 Very willing")) %>% 
  group_by(accept) %>%
   summarize(N_obs = n()) %>% 
  mutate(Percent_obs = round(N_obs/(sum(N_obs))*100)) %>% 
  kable(booktabs = TRUE, linesep = "", escape = F, caption = "How willing are you to accept and follow the decision?", col.names = linebreak(c("Value", "N", "Percent")))%>% 
  kable_styling(latex_options = "HOLD_position")


d %>% mutate(
  accept = case_when(
      accept == 1 ~ "1 Not willing at all",
      accept == 2 ~ "2",
      accept == 3 ~ "3",
      accept == 4 ~ "4",
      accept == 5 ~ "5",
      accept == 6 ~ "6",
      accept == 7 ~ "7 Very willing")) %>% 
  group_by(accept) %>%
   summarize(N_obs = n()) %>% 
  mutate(Percent_obs = round(N_obs/(sum(N_obs))*100)) %>% 
  kable(booktabs = TRUE, linesep = "", escape = F, caption = "What do you think about the way the decision was made?", col.names = linebreak(c("Value", "N", "Percent")))%>% 
  kable_styling(latex_options = "HOLD_position") %>% 
  cat(., file = here("output", "swevig", "tbls", "html", "tbl-dv-accept-swevig.html"))
```
The mean score for the post treatment measure "What do you think about the way the decision was made?" is `r round(mean(d$accept), digits=2)`, and the standard deviation is `r round(sd(d$accept), digits=2)`.



\newpage
## Effects on losers

Treatment effects on experimental subjects who find the decision outcome to align unfavorably with their own preferences.
```{r, 1051_outfav}
#Keep object with both winners and losers
e <- d
#Filter on respondents who receive an unfavorable outcome in object 
d <- d %>% 
  filter(favorability == "Unfavorable") 
```

### Fairness

#### Fairness - Figure 2

> Figure 2 in the manuscript (Figure 1 appears towards the end of the appendix):

```{r 1052_post_fairness}
#Figure
fig <- d %>% 
  ggplot(aes(x = treatment, y = fairness)) +
  stat_summary(fun.data = mean_cl_normal, geom = 'point') +
  stat_summary(fun.data = mean_cl_normal, geom = 'linerange') +
  scale_y_continuous(limits = c(1, 7),
                     breaks = 1:7, 
                     labels = c('1 Not fair at all', '2', '3', '4', '5', '6', '7 Very fair')) +
  labs(x = " ",
       y = "",
       title = "", #Treatment groups and mean fairness perceptions of decision, Study 1
       subtitle = '', #Sample: Respondents who receive an unfavorable outcome.
       caption = '') + #Error bars represent 95% confidence intervals.
  theme_bw() +
  coord_flip()
fig

#Save figure in png and pdf format
ggsave("figure2-exp1-fairness-losers.png",
  plot = fig,
  width = 8, height = 2.75, units = "in", dpi = 600
)

# Linear regression with heteroscedasticity-consistent standard errors using the estimatr package
res_main <-  lm_robust(fairness ~ treatment, data = d)
res_main <- broom::tidy(res_main)

#Table
labels <- data.frame(
  term = c(
    "treatmentLamenting politician",
    "treatmentGeneral prime",
    "Not shown"

  ),
  label = c( "Lamenting politician",
             "Generic good loser message",
             "Not shown")
)

table <- res_main %>%
  select(term, estimate, std.error, statistic, p.value) %>%
  mutate(term = case_when( term == "(Intercept)" ~ "Not shown",
                    term == "treatmentLamenting politician" ~ "Lamenting politician",
                   term == "treatmentGeneral prime" ~ "Generic good loser message")
         )

kable(table, booktabs = TRUE, caption = "Treatment effects on fairness perceptions of decision, Study 1", col.names = linebreak(c("Treatment value", "Estimate", "Std. Error", "t-statistic", "p value")), digits = 2) %>%
  kable_styling(bootstrap_options = c("striped", "hover", "responsive"))
#save to file
kable(table, booktabs = TRUE, caption = "Treatment effects on fairness perceptions of decision, Study 1", col.names = linebreak(c("Treatment value", "Estimate", "Std. Error", "t-statistic", "p value")), digits = 2) %>%
  kable_styling(bootstrap_options = c("striped", "hover", "responsive")) %>%
  cat(., file = here("output", "swevig", "tbls", "html",  "tbl-losers-fairness-swevig.html"))

f <- d %>% mutate(treatment = lvls_reorder(treatment, c(2, 1 , 3)))

res_main <-  lm_robust(fairness ~ treatment, data = f) 
res_main <- broom::tidy(res_main)

labels <- data.frame(
  term = c(
    "treatmentNot shown",
    "treatmentGeneral prime"
    
  ),
  label = c( "Not shown",
             "Generic good loser message")
)

#Table
table <- res_main %>% 
  select(term, estimate, std.error, statistic, p.value) %>% 
  mutate(term = case_when( term == "(Intercept)" ~ "Intercept",
                    term == "treatmentNot shown" ~ "Not shown",
                   term == "treatmentGeneral prime" ~ "Generic good loser message")
         )

#for bookdown
kable(table, booktabs = TRUE, caption = "Treatment effects on fairness perceptions of decision, Study 1", col.names = linebreak(c("Treatment value", "Estimate", "Std. Error", "t-statistic", "p value")), digits = 2) %>% 
  kable_styling(bootstrap_options = c("striped", "hover", "responsive")) %>% 
  footnote(general = 'Lamenting politician set as reference category.')
#save to file
kable(table, booktabs = TRUE, caption = "Treatment effects on fairness perceptions of decision, Study 1", col.names = linebreak(c("Treatment value", "Estimate", "Std. Error", "t-statistic", "p value")), digits = 2) %>% 
  kable_styling(bootstrap_options = c("striped", "hover", "responsive")) %>% 
  footnote(general = 'Lamenting politician set as reference category.') %>% 
  cat(., file = here("output", "swevig", "tbls", "html",  "tbl-losers-fairness-swevig.html"))

```


#### Fairness - including covariates
```{r 1053_post_fairness_covariates}
# Regression including covariates. Linear regression with heteroscedasticity-consistent standard errors using the estimatr package
res_main <-  lm_robust(fairness ~ treatment + polint + leftright + age + gender + education, data = d)
res_main <- broom::tidy(res_main)

#Table
table <- res_main %>%
  select(term, estimate, std.error, statistic, p.value) %>%
  mutate(term = case_when( term == "(Intercept)" ~ "Not shown",
                    term == "treatmentLamenting politician" ~ "Lamenting politician",
                   term == "treatmentGeneral prime" ~ "Generic good loser message",
                   term == 'polint' ~ 'Political interest',
                   term == 'leftright' ~ 'Left/right scale',
                   term == 'age' ~ 'Age',
                   term == 'gender' ~ 'Gender',
                   term == 'education' ~ 'Education')
         )

kable(table, booktabs = TRUE, caption = "Treatment effects on fairness perceptions of decision, Study 1. Including covariates.", col.names = linebreak(c("Treatment value", "Estimate", "Std. Error", "t-statistic", "p value")), digits = 2) %>%
  kable_styling(bootstrap_options = c("striped", "hover", "responsive")) %>% 
  footnote('Political interest from 1 (lowest) to 4 (highest); Left/right self-placement from 1 (leftmost) to 10 (rightmost); Age in continous integers from 18 upwards; gender as dichotomous variable where 0 is male and 1 is female; education as dichotomous variable where 0 is no higher education and 1 is higher education.' )
#save to file
kable(table, booktabs = TRUE, caption = "Treatment effects on fairness perceptions of decision, Study 1. Including covariates.", col.names = linebreak(c("Treatment value", "Estimate", "Std. Error", "t-statistic", "p value")), digits = 2) %>%
  kable_styling(bootstrap_options = c("striped", "hover", "responsive")) %>%
    footnote('Political interest from 1 (lowest) to 4 (highest); Left/right self-placement from 1 (leftmost) to 10 (rightmost); Age in continous integers from 18 upwards; gender as dichotomous variable where 0 is male and 1 is female; education as dichotomous variable where 0 is no higher education and 1 is higher education.' ) %>% 
  cat(., file = here("output", "swevig", "tbls", "html",  "tbl-losers-fairness-swevig-covariates.html"))
```

#### Fairness - winners

> Similar analysis, this time with winners:

```{r 1054_post_fairness_alt2}

w <- e %>% filter(favorability == "Favorable") 
  
  #Figure
fig <- w %>% 
  ggplot(aes(x = treatment, y = fairness)) +
  stat_summary(fun.data = mean_cl_normal, geom = 'point') +
  stat_summary(fun.data = mean_cl_normal, geom = 'linerange') +
  scale_y_continuous(limits = c(1, 7),
                     breaks = 1:7, 
                     labels = c('1 Not fair at all', '2', '3', '4', '5', '6', '7 Very fair')) +
  labs(x = " ",
       y = "",
       title = "Treatment groups and mean fairness perceptions of decision, Study 1",
       subtitle = 'Sample: Winners.',
       caption = 'Error bars represent 95% confidence intervals.') +
  theme_bw() +
  coord_flip()
fig

ggsave("exp1-fairness-winners.png",
  plot = fig,
  width = 7, height = 2.75
)

# Linear regression with heteroscedasticity-consistent standard errors using the estimatr package
res_main <-  lm_robust(fairness ~ treatment, data = w)
res_main <- broom::tidy(res_main)

# Table
table <- res_main %>%
  select(term, estimate, std.error, statistic, p.value) %>%
  mutate(term = case_when( term == "(Intercept)" ~ "Not shown",
                    term == "treatmentLamenting politician" ~ "Lamenting politician",
                   term == "treatmentGeneral prime" ~ "Generic good loser message")
         )

kable(table, booktabs = TRUE, caption = "Treatment effects on fairness perceptions of decision, Study 1. Sample: Winners", col.names = linebreak(c("Treatment value", "Estimate", "Std. Error", "t-statistic", "p value")), digits = 2) %>%
  kable_styling(bootstrap_options = c("striped", "hover", "responsive"))

# save to file
kable(table, booktabs = TRUE, caption = "Treatment effects on fairness perceptions of decision, Study 1. Sample: Winners", col.names = linebreak(c("Treatment value", "Estimate", "Std. Error", "t-statistic", "p value")), digits = 2) %>%
  kable_styling(bootstrap_options = c("striped", "hover", "responsive")) %>%
  cat(., file = here("output", "swevig", "tbls", "html",  "tbl-fairness-swevig.html"))
```

#### Fairness - moderated by issue importance
```{r 1054_fairness_importance}

res <- lm_robust(fairness ~ treatment*opinion_strength, data = d)

fig <- summary(margins(res, at = list(opinion_strength = 1:7)))  %>% 
  filter(factor == 'treatmentGeneral prime') %>% 
    ggplot(aes(x = AME, y = opinion_strength,
               xmin = AME - (2 * SE) ,
               xmax = AME + (2 * SE))) +
  coord_flip() +
   geom_errorbarh(height = 0) +
  geom_point() +
  geom_vline(aes(xintercept = 0), linetype = "dotted") +
  scale_x_continuous(limits = c(-1, 2),
                     breaks = round(seq(-1, 2, 0.5), 1),
                     expand = c(0, 0)) +
  scale_y_continuous(limits = c(0.5, 7.5),
                     breaks = round(seq(-1, 7, 1), 1),
                     expand = c(0, 0)) +

  labs(x = 'AME',
       y = "Issue importance, from 1 (lowest) to 7 (highest)",
       title = "Generic good loser message") +
  theme_bw() +
 # theme(plot.title = element_text(size=9), plot.subtitle = element_text(size=8), plot.margin = unit(c(2, 2, 2, 2), "mm"), axis.text.x=element_text(size=rel(0.7))) +
  theme(panel.spacing = unit(0.5, "lines"))
fig

ggsave("exp1-fairness-importance-int-generalprime-losers.png",
  plot = fig,
  width = 7, height = 2.75
)
```


### Acceptance
```{r 1055_post_accept}

#Figure
fig <- d %>% 
  ggplot(aes(x = treatment, y = accept)) +
  stat_summary(fun.data = mean_cl_normal, geom = 'point') +
  stat_summary(fun.data = mean_cl_normal, geom = 'linerange') +
  scale_y_continuous(limits = c(1, 7),
                     breaks = 1:7,
                     labels = c('1 Not willing at all', '2', '3', '4', '5', '6', '7 Very willing')) +
  labs(x = '',
       y = '',
       title = "Treatment effects on willingness to accept decision, Study 1",
       subtitle = 'Sample: Respondents who receive an unfavorable outcome.',
       caption = 'Error bars represent 95% confidence intervals.') +
  theme_bw() +
  coord_flip()
fig  
  
ggsave("exp1-accept-losers.png",
  plot = fig,
  width = 7, height = 2.75
)

# Linear regression
res_main <-  lm_robust(accept ~ treatment, data = d) 
res_main <- broom::tidy(res_main)

#Table
table <- res_main %>% 
  select(term, estimate, std.error, statistic, p.value) %>% 
  mutate(term = case_when( term == "(Intercept)" ~ "Not shown",
                    term == "treatmentLamenting politician" ~ "Lamenting politician",
                   term == "treatmentGeneral prime" ~ "Generic good loser message")
         )

kable(table, booktabs = TRUE, caption = "Treatment effects on willingness to accept decision, Study 1", col.names = linebreak(c("Treatment value", "Estimate", "Std. Error", "t-statistic", "p value")), digits = 2) %>% 
  kable_styling(bootstrap_options = c("striped", "hover", "responsive"))
#save to file
kable(table, booktabs = TRUE, caption = "Treatment effects on willingness to accept decision, Study 1", col.names = linebreak(c("Treatment value", "Estimate", "Std. Error", "t-statistic", "p value")), digits = 2) %>% 
  kable_styling(bootstrap_options = c("striped", "hover", "responsive")) %>% 
  cat(., file = here("output", "swevig", "tbls", "html",  "tbl-losers-acceptance-swevig.html"))
```

#### Willingness to accept - including covariates
```{r 1056_post_accept_covariate}
# Linear regression
res_main <-  lm_robust(accept ~ treatment  + polint + leftright + age + gender + education, data = d) 
res_main <- broom::tidy(res_main)

#Table
table <- res_main %>%
  select(term, estimate, std.error, statistic, p.value) %>%
  mutate(term = case_when( term == "(Intercept)" ~ "Not shown",
                    term == "treatmentLamenting politician" ~ "Lamenting politician",
                   term == "treatmentGeneral prime" ~ "Generic good loser message",
                   term == 'polint' ~ 'Political interest',
                   term == 'leftright' ~ 'Left/right scale',
                   term == 'age' ~ 'Age',
                   term == 'gender' ~ 'Gender',
                   term == 'education' ~ 'Education')
         )
kable(table, booktabs = TRUE, caption = "Treatment effects on willingness to accept decision, Study 1. Including covariates.", col.names = linebreak(c("Treatment value", "Estimate", "Std. Error", "t-statistic", "p value")), digits = 2) %>% 
  kable_styling(bootstrap_options = c("striped", "hover", "responsive")) %>% 
  footnote('Political interest from 1 (lowest) to 4 (highest); Left/right self-placement from 1 (leftmost) to 10 (rightmost); Age in continous integers from 18 upwards; gender as dichotomous variable where 0 is male and 1 is female; education as dichotomous variable where 0 is no higher education and 1 is higher education.' )

#save to file
kable(table, booktabs = TRUE, caption = "Treatment effects on willingness to accept decision, Study 1. Including covariates.", col.names = linebreak(c("Treatment value", "Estimate", "Std. Error", "t-statistic", "p value")), digits = 2) %>% 
  kable_styling(bootstrap_options = c("striped", "hover", "responsive")) %>% 
  footnote('Political interest from 1 (lowest) to 4 (highest); Left/right self-placement from 1 (leftmost) to 10 (rightmost); Age in continous integers from 18 upwards; gender as dichotomous variable where 0 is male and 1 is female; education as dichotomous variable where 0 is no higher education and 1 is higher education.' ) %>% 
  cat(., file = here("output", "swevig", "tbls", "html",  "tbl-losers-acceptance-swevig-covariates.html"))
```

\newpage
## Differential attrition check

There was no attrition in this study, making a differential attrition analysis redundant.

\newpage
# STUDY II 

The experiment for Study II was fielded in Norway during the spring and fall of 2017 during the 9th and 10th waves of [Norwegian Citizen Panel](https://www.uib.no/medborger). This is a research-purpose internet panel with over 6000 active participants. 
It is based on a probability sample of the general Norwegian population above the age of 18 drawn from the Norwegian National Registry.
The survey is based on a online questionnaire with postal recruitment. 
Panel members complete a questionnaire three times a year of 15 minutes each. 
The survey panel is a core component of The Digital Social Science Core Facilities (DIGSSCORE), and  was established in 2013 as a collaboration between several departments at the Faculty of Social Sciences at the University of Bergen and NORCE -- Norwegian Research Centre.
We refer to the [documentation report](Data/ncp-wave13-documentation.pdf) for further details on technical aspects of the survey, panel recruitment, response rates of the 13th wave, and representativeness. 
For details about the data collected in this project and the survey panel at large, we refer to the [codebook for the Waves 1-13](Data/ncp-wave13-codebook.pdf).

```{r 2010_import, eval= FALSE}
ncp_raw <- read_sav(here("Data", "Norwegian Citizen Panel - wave 1-13 - EN.sav"))
```

```{r 2011_prepare, eval= FALSE}
d <- ncp_raw %>%
  select(responseid,
         "polint" = "r9k1",
          "gender" = "R9P1",
          "age" = "R9P5_2",
          "imp_accept"= "r9pad1",
          "other_accept" = "r9pad2",
          "self_accept" = "r9pad3",
          "opinion_ban" = "r10pad1",
          "opinion_strength" = "r10pad2",
          "video_mobile" = "r10pad3_mobil",
          "video_proban_treat" = "r10pad3a_ran",
          "video_antiban_treat" = "r10pad3b_ran",
          "video_ended" = "r10pad3ended",
          "video_error" = "r10pad3error",
          "video_paused" = "r10pad3paused",
          "video_played" = "r10pad3played",
          "video_timespent" = "r10pad3_timespent",
          "video_report" = "r10pad4",
          "fairness" = "r10pad5",
          "accept" = "r10pad6",
          "trust" = "r10pad7",
          "check_outcome" = "r10pad8",
          "check_politician" = "r10pad9",
         r10pad1_9_backward_1, 
         r10pad1_9_backward_2, 
         r10pad1_9_backward_3, 
         r10pad1_9_backward_4, 
         r10pad1_9_backward_5, 
         r10pad1_9_backward_6, 
         r10pad1_9_backward_7, 
         r10pad1_9_backward_8
  )

#Merge treatments with ban and no ban outcomes          
d <- d %>%
  pivot_longer(video_proban_treat:video_antiban_treat, names_to = 'video', values_to = 'treatment')

#Make NA the respondents with values 98 (Not asked) or 97 (No answer) for entire dataset. (Checked with command 'sum(is.na(Loser$video_timespent)) that no values on that variable has value 97 or 98)
d[d == 97] <- NA
d[d == 98] <- NA

#Reverse scales
d <- d %>%
  mutate(imp_accept = 6-(imp_accept),
         other_accept = 6-(other_accept),
         self_accept = 6-(self_accept),
         opinion_strength = 6-(opinion_strength),
         fairness = 6-(fairness),
         accept = 6-(accept),
         trust = 6-(trust),
         polint = 6-(polint)
  )

##Create manipulation check variable that measures whether the respondents correctly identify whether the outcome was favorable or unfavorable to them
d <- d %>%
  mutate(favorability = case_when(
    treatment %in% 1:4 ~ "Unfavorable",
    treatment == 5    ~ "Favorable"),
    mcheck_favorability = case_when(
    is.na(favorability) ~ "Incorrect",
    favorability=="Favorable" & check_outcome==1 ~ "Correct",
    favorability=="Unfavorable" & check_outcome==2 ~ "Correct",
    favorability %in% 3:4 ~ "Incorrect",
    favorability=="Favorable" & check_outcome==2 ~ "Incorrect",
    favorability=="Unfavorable" & check_outcome==1 ~ "Incorrect")
  ) 

#Label variable values
d <- d %>%
  mutate(treatment = case_when(
    .[["treatment"]] == 1 ~ "Lamenting politician",
    .[["treatment"]] == 2 ~ "Specific prime",
    .[["treatment"]] == 3 ~ "General Prime",
    .[["treatment"]] == 4 ~ "Not shown",
    .[["treatment"]] == 5 ~ "Winner"),
    opinion_ban = case_when(
    .[["opinion_ban"]] == 1 ~ "Pro",
    .[["opinion_ban"]] == 2 ~ "Anti"),
    responseid = as.numeric(responseid),
    imp_accept_1 = case_when(
      imp_accept == 1 ~ "Not important at all",
      imp_accept == 2 ~ "Slightly important",
      imp_accept == 3 ~ "Somewhat important",
      imp_accept == 4 ~ "Important",
      imp_accept == 5 ~ "Very important"),
    imp_accept_1 = lvls_reorder(factor(imp_accept_1), c(2, 3, 4, 1, 5)),
    imp_accept_2 = case_when(imp_accept %in% 4:5 ~ "Important",
                            imp_accept %in% 1:3 ~ "Not important"),
    other_accept_1 = case_when(
      other_accept == 1 ~ "Not at all",
      other_accept == 2 ~ "Low degree",
      other_accept == 3 ~ "Some degree",
      other_accept == 4 ~ "High degree",
      other_accept == 5 ~ "Very high degree"),
    other_accept_1 = lvls_reorder(factor(other_accept_1), c(3, 2, 4, 1, 5)),
    other_accept_2 = case_when(other_accept %in% 4:5 ~ "High degree",
                              other_accept %in% 1:3 ~ "Low degree"),
    self_accept_1 = case_when(
      self_accept == 1 ~ "Not at all",
      self_accept == 2 ~ "Low degree",
      self_accept == 3 ~ "Some degree",
      self_accept == 4 ~ "High degree",
      self_accept == 5 ~ "Very high degree"),
    self_accept_1 = lvls_reorder(factor(self_accept_1), c(3, 2, 4, 1, 5)),
    self_accept_2 = case_when(self_accept %in% 4:5 ~ "High degree",
                             self_accept %in% 1:3 ~ "Low degree"),
    opinion_strength_1 = case_when(
      opinion_strength == 1 ~ "Not important at all",
      opinion_strength == 2 ~ "Slightly important",
      opinion_strength == 3 ~ "Somewhat important",
      opinion_strength == 4 ~ "Important",
      opinion_strength == 5 ~ "Very important"),
    opinion_strength_1 = lvls_reorder(factor(opinion_strength_1), c(2, 3, 4, 1, 5)),
    opinion_strength_2 = case_when(opinion_strength %in% 4:5 ~ "Important",
                                  opinion_strength %in% 1:3 ~ "Not important")
  )
```

```{r, 2012_datasets, eval= FALSE}

# Keep a full ITT dataset, including winners and losers
d <- d %>%
  filter(!is.na(treatment)) #Keep all who where assigned to a video treatment

export(d, here("Data", "Goodloser-exp2.rds"))
```

```{r, 2013_reload}

d <- import(here("Data", "Goodloser-exp2.rds"))

#Remove respondents who did not see the video properly. 
e <- d %>% filter(video_timespent %in% 60:300) %>% #Keep only those who stayed with the video for more than 60 seconds and less than 300 seconds
  filter(video_report %in% c(1, 3)) #Keep only those who reported that they had sound and picture or picture but no sound

#Create a separate data set where also those who fail the manipulation check are excluded.
f <- e %>%
  filter(mcheck_favorability == "Correct")
```
\newpage
## Pre-treatment measures
### Good loser norm I
```{r 2021_goodloserI, paged.print=TRUE}
table <- d %>% 
  group_by(imp_accept_1) %>%
   summarize(N_obs = n()) %>% 
  mutate(Percent_obs = round(N_obs/(sum(N_obs))*100))

kable(table, booktabs = TRUE, linesep = "", escape = F, caption = "What is your opinion – how important is it to accept the decisions about important social issues after they have been adopted?", col.names = linebreak(c("Value", "N", "Percent"))) %>% 
  kable_styling(latex_options = "HOLD_position") 
#save to file
kable(table, booktabs = TRUE, linesep = "", escape = F, caption = "What is your opinion – how important is it to accept the decisions about important social issues after they have been adopted?", col.names = linebreak(c("Value", "N", "Percent"))) %>% 
  kable_styling(latex_options = "HOLD_position") %>% 
  cat(., file = here("output", "novig", "tbls", "html",  "tbl-novig-imp-accept.html"))
```
The mean score for the pre treatment measure "What is your opinion – how important is it to accept the decisions about important social issues after they have been adopted?" is `r round(mean(d$imp_accept, na.rm=T), digits=2)`, and the standard deviation is `r round(sd(d$imp_accept, na.rm=T), digits=2)`.

### Good loser norm II
```{r 2022_goodloserII}
table <- d %>% 
    group_by(other_accept_1) %>%
   summarize(N_obs = n()) %>% 
  mutate(Percent_obs = round(N_obs/(sum(N_obs))*100))

  kable(table, booktabs = TRUE, linesep = "", escape = F, caption = "To what extent do you think people in Norway are willing to accept the decisions about important social issues after they have been adopted by politicians and the authorities?", col.names = linebreak(c("Value", "N", "Percent")))%>% 
  kable_styling(latex_options = "HOLD_position") 

  #save to file
  kable(table, booktabs = TRUE, linesep = "", escape = F, caption = "To what extent do you think people in Norway are willing to accept the decisions about important social issues after they have been adopted by politicians and the authorities?", col.names = linebreak(c("Value", "N", "Percent")))%>% 
  kable_styling(latex_options = "HOLD_position") %>% 
  cat(., file = here("output", "novig", "tbls", "html",  "tbl-novig-other-accept.html"))
```

The mean score for the pre treatment measure "To what extent do you think people in Norway are willing to accept the decisions about important social issues after they have been adopted by politicians and the authorities?" is `r round(mean(d$other_accept, na.rm=T), digits=2)`, and the standard deviation is `r round(sd(d$other_accept, na.rm=T), digits=2)`.

### Good loser norm III
```{r 2023_goodloserIII}
table <- d %>% 
  group_by(self_accept_1) %>%
   summarize(N_obs = n()) %>% 
  mutate(Percent_obs = round(N_obs/(sum(N_obs))*100)) 

  kable(table, booktabs = TRUE, linesep = "", escape = F, caption = "What about you personally – do you live up to this standard (i.e., accept the decisions about important social issues after they have been adopted by politicians and the authorities)?", col.names = linebreak(c("Value", "N", "Percent"))) %>% 
  kable_styling(latex_options = "HOLD_position") 
#save to file  
  kable(table, booktabs = TRUE, linesep = "", escape = F, caption = "What about you personally – do you live up to this standard (i.e., accept the decisions about important social issues after they have been adopted by politicians and the authorities)?", col.names = linebreak(c("Value", "N", "Percent"))) %>% 
  kable_styling(latex_options = "HOLD_position") %>% 
  cat(., file = here("output", "novig", "tbls", "html",  "tbl-novig-self-accept.html"))
```

The mean score for the pre treatment measure "What about you personally – do you live up to this standard (i.e., accept the decisions about important social issues after they have been adopted by politicians and the authorities)?" is `r round(mean(d$self_accept, na.rm=T), digits=2)`, and the standard deviation is `r round(sd(d$self_accept, na.rm=T), digits=2)`.

### Ban on begging - opinion
```{r 2024_begging}
table <- d %>%  
group_by(opinion_ban) %>%
   summarize(N_obs = n()) %>% 
  mutate(Percent_obs = round(N_obs/(sum(N_obs))*100)) %>%
  ungroup()  

  kable(table, booktabs = TRUE, linesep = "", escape = F, caption = "What is your opinion on a ban on begging in your municipality?", col.names = linebreak(c("Value", "N", "Percent"))) %>% 
  kable_styling(latex_options = "HOLD_position") 
 
#save to file
   kable(table, booktabs = TRUE, linesep = "", escape = F, caption = "What is your opinion on a ban on begging in your municipality?", col.names = linebreak(c("Value", "N", "Percent"))) %>% 
  kable_styling(latex_options = "HOLD_position") %>% 
  cat(., file = here("output", "novig", "tbls", "html",  "tbl-novig-begging-pref.html"))
```

### Ban on begging - importance
```{r 2025_beggingop}
table <- d %>% 
  group_by(opinion_strength_1) %>%
   summarize(N_obs = n()) %>% 
  mutate(Percent_obs = round(N_obs/(sum(N_obs))*100)) %>%
  ungroup()  

kable(table, booktabs = TRUE, linesep = "", escape = F, caption = "How important is this issue to you personally?", col.names = linebreak(c("Value", "N", "Percent"))) %>% 
  kable_styling(latex_options = "HOLD_position")

#save to file
kable(table, booktabs = TRUE, linesep = "", escape = F, caption = "How important is this issue to you personally?", col.names = linebreak(c("Value", "N", "Percent"))) %>% 
  kable_styling(latex_options = "HOLD_position")%>% 
  cat(., file = here("output", "novig", "tbls", "html",  "tbl-novig-begging-importance.html"))
```

The mean score for the pre treatment measure "How important is this issue to you personally?" is `r round(mean(d$opinion_strength, na.rm=T), digits=2)`, and the standard deviation is `r round(sd(d$opinion_strength, na.rm=T), digits=2)`.

\newpage
## Experimental vignette
```{r 2030_vignette}

table <- tibble(Preference = c("Pro ban on begging", "Pro ban on begging", "Pro ban on begging", "Pro ban on begging", "Pro ban on begging", "Against ban on begging", "Against ban on begging", "Against ban on begging", "Against ban on begging", "Against ban on begging"), 
                Treatment = c("No prime", "Lamenting politician", "Generic good loser prime", "Specific good loser prime", "Winner", "No prime", "Lamenting politician", "Generic good loser prime", "Specific good loser prime", "Winner"), 
                Text = c("The majority votes against a ban on begging. That means the council will not ban begging in your municipality.",
                         "The majority votes against a ban on begging. That means the council will not ban begging in your municipality. After the decision, the leader of one of the parties who where in favor of a ban states that they are disappointed and that the decision was wrong.",
                         "The majority votes against a ban on begging. That means the council will not ban begging in your municipality. After the decision, the leader of one of the parties who where in favor of a ban states that they are disappointed and that the decision was wrong, but that's how it is like living in a democracy. Sometimes you win, sometimes you lose.",
                         "The majority votes against a ban on begging. That means the council will not ban begging in your municipality. After the decision, the leader of one of the parties who where in favor of a ban states that they are disappointed and that the decision was wrong, but that it was a fair fight where both sides had the chance to defend their positions.",
                         "The majority votes for a ban on begging. That means the council will ban begging in your municipality.",
                         "The majority votes for a ban on begging. That means the council will ban begging in your municipality.", 
                         "The majority votes for a ban on begging. That means the council will ban begging in your municipality. After the decision, the leader of one of the parties who where in favor of a ban states that they are disappointed and that the decision was wrong.", 
                         "The majority votes for a ban on begging. That means the council will ban begging in your municipality. After the decision, the leader of one of the parties who where in favor of a ban states that they are disappointed and that the decision was wrong, but that's how it is like living in a democracy. Sometimes you win, sometimes you lose.",
                         "The majority votes for a ban on begging. That means the council will ban begging in your municipality. After the decision, the leader of one of the partieswho where in favor of a ban states that they are disappointed and that the decision was wrong, but that it was a fair fight where both sides had the chance to defend their positions.",
                         "The majority votes against a ban on begging. That means the council will not ban begging in your municipality.")
)

   table %>% 
    mutate_all(linebreak) %>% 
    kable(booktabs = T, linesep = "", escape = F,  caption = "Video vignette treatment dimensions and values.", col.names = linebreak(c("Preference", "Treatment", "Text"))) %>% 
    collapse_rows(columns = 1, latex_hline = "major", valign = "top") %>% 
    
  kable_styling(latex_options = c("scale_down", "HOLD_position")) %>% 
        footnote(number =  c('Intro to all respondents: Imagine that your municipality is about to decide whether begging on the streets should be banned or allowed within the municipal borders in the future. This is a controversial decision: Some inhabitants and politicians strongly support the ban, while other inhabitants and politicians are equally strongly against such a ban on begging. Some parties propose a ban on begging. The decision will be made in the municipal council, and follows the normal decision-making procedure. The proposal is  first debated in the council, where all members are welcome to express their position and their arguments. The debate is public, and journalists are present to report on the debate. In the end, the politicians vote on the proposal.',
                 'Video voice over text (video was subtitled).'))
#save to file
  table %>% 
    mutate_all(linebreak) %>% 
    kable(booktabs = T, linesep = "", escape = F,  caption = "Video vignette treatment dimensions and values.", col.names = linebreak(c("Preference", "Treatment", "Text"))) %>% 
    collapse_rows(columns = 1, latex_hline = "major", valign = "top") %>% 
    
  kable_styling(latex_options = c("scale_down", "HOLD_position")) %>% 
        footnote(number =  c('Intro to all respondents: Imagine that your municipality is about to decide whether begging on the streets should be banned or allowed within the municipal borders in the future. This is a controversial decision: Some inhabitants and politicians strongly support the ban, while other inhabitants and politicians are equally strongly against such a ban on begging. Some parties propose a ban on begging. The decision will be made in the municipal council, and follows the normal decision-making procedure. The proposal is  first debated in the council, where all members are welcome to express their position and their arguments. The debate is public, and journalists are present to report on the debate. In the end, the politicians vote on the proposal.',
                 'Video voice over text (video was subtitled).')) %>% 
    cat(., file = here("output", "novig", "tbls", "html",  "tbl-novig-design.html"))
```

### Random assignment to treatment groups
As described in the methodology report of the Norwegain Citizen Panel [see @skjervheim2017, pp. 2-3], we here lay out the procedure for random assignment to treatment conditions in Studies 2 and 3.

All randomization procedures in The Norwegian Citizen Panel are executed live in the online questionnaire. 
This means that the randomization takes place while the respondent is in the questionnaire, as opposed to pre-defined randomizations that are uploaded to the questionnaire. 
All randomizations are independent from another, unless the documentation states otherwise.

The randomization procedures are written in JavaScript. 
Math.random() is a key function, in combination with Math.floor()
These functions are used to randomly select one value from a vector.

Say for example we wish to create two groups of respondents: group 1 and group 2. 
All respondents are randomly assigned the value 1 or 2, where each randomization is independent from one another. 
When N is large enough these two groups will be of equal size (50/50). 

```{js 2031_randomization, eval = FALSE, echo = TRUE}
var form = f("x1");
if(!form.toBoolean()) // If no previous randomization on x1
{
  var precodes = x1.domainValues(); //Copies the length of x1
  var randomNumber : float = Math.random()*precodes.length;
  var randomIndex : int = Math/floor(randomNumber);
  form.set(code);
}
```

### Descriptive information about treatment groups
```{r 2032_balance}
  
fig1 <- d %>% mutate(gender = as.numeric(gender)-1,
                      treatment = lvls_reorder(treatment, c(3, 2, 5, 4, 1))) %>% 
  ggplot(aes(x = treatment, y = gender)) +
stat_summary(fun.data = mean_cl_normal, geom = 'linerange') +
  stat_summary(fun.data = mean_cl_normal, geom = 'point') +
  scale_y_discrete(limits = c(0,1),
                   breaks = seq(from = 0, to = 1, by = 0.2)) +
  labs(x = '',
       y = '',
       title = 'Gender',
       subtitle = 'Proportion Females') +
  theme_bw() +
  coord_flip()

#Age
fig2 <- d %>% mutate(age = as.character(case_when(age == 1 ~ "<1960",
                                                  age == 2 ~ "1960-1989",
                                                  age == 3 ~ ">1989")),
                     treatment = lvls_reorder(treatment, c(3, 2, 5, 4, 1)),
                     treatment = case_when(treatment == 'Specific prime' ~ 'Specific \nprime',
                                           treatment == 'Lamenting politician' ~ 'Lamenting \npolitician',
                                           treatment == 'General Prime' ~ 'General \nprime',
                                           treatment == 'Not shown' ~ 'Not shown',
                                           treatment == 'Winner' ~ 'Winner'),
                     age = lvls_reorder(age, c(1, 3, 2))) %>% 
  filter(!is.na(treatment)) %>% 
  ggplot(aes(x = age)) +
  geom_bar(aes(y = (..count..)/sum(..count..))) + 
          scale_y_continuous(labels=scales::percent) +
    labs(x = '',
       y = '',
       title = 'Birth Year') +
  scale_x_discrete(guide = guide_axis(n.dodge = 3)) + 
  theme_bw() +
  facet_wrap(~treatment)

#Political interest
fig3 <- d %>% mutate(treatment = lvls_reorder(treatment, c(3, 2, 5, 4, 1))) %>% 
                       ggplot(aes(x = treatment, y = polint)) +
stat_summary(fun.data = mean_cl_normal, geom = 'linerange') +
  stat_summary(fun.data = mean_cl_normal, geom = 'point') +
  scale_y_continuous(limits = c(1,5),
                   labels = c('Not interested at all',
                              '',
                              '',
                              '',
                              'Very \ninterested')) +
  labs(x = '',
       y = '',
       title = "Political interest"
       ) +
theme_bw() +
  coord_flip()

patchwork <- fig2 + fig1 / fig3
patchwork + plot_annotation(title = 'Descriptive information about treatment groups')

#Save figure in png and pdf format
ggsave("exp2-balance.png",
  plot = fig3,
  width = 7, height = 2.75
)
```

\newpage
## Post-treatment measures
### Fairness

```{r 2040_fairness}
table <- d %>% mutate(
   fairness = case_when(fairness == 1 ~ "Not at all fair",
                         fairness == 2 ~ "Not very fair",
                         fairness == 3 ~ "Quite fair",
                         fairness == 4 ~ "Fair",
                         fairness == 5 ~ "Very fair"),
    fairness = lvls_reorder(factor(fairness), c(2, 3, 4, 1, 5))) %>% 
  group_by(fairness) %>%
   summarize(N_obs = n()) %>% 
  mutate(Percent_obs = round(N_obs/(sum(N_obs))*100))

kable(table, booktabs = TRUE, linesep = "", escape = F, caption = "What do you think about the way the decision was made?", col.names = linebreak(c("Value", "N", "Percent")))%>% 
  kable_styling(latex_options = "HOLD_position") 

#save to file  
kable(table, booktabs = TRUE, linesep = "", escape = F, caption = "What do you think about the way the decision was made?", col.names = linebreak(c("Value", "N", "Percent")))%>% 
  kable_styling(latex_options = "HOLD_position") %>% 
  cat(., file = here("output", "novig", "tbls", "html",  "tbl-novig-fairness-dv.html"))
```
The mean score for the post treatment measure "What do you think about the way the decision was made?" is `r round(mean(d$fairness, na.rm=T), digits=2)`, and the standard deviation is `r round(sd(d$fairness, na.rm=T), digits=2)`.

### Acceptance
```{r 2041_acceptance}
table <- d %>% mutate(
   accept = case_when(accept == 1 ~ "Not at all willing",
                        accept == 2 ~ "Not very willing",
                        accept == 3 ~ "Quite willing", 
                        accept == 4 ~ "Willing", 
                        accept == 5 ~ "Very willing"),
    accept = lvls_reorder(factor(accept), c(1, 2, 3, 5, 4))) %>% 
  group_by(accept) %>%
   summarize(N_obs = n()) %>% 
  mutate(Percent_obs = round(N_obs/(sum(N_obs))*100)) 

kable(table, booktabs = TRUE, linesep = "", escape = F, caption = "When you think about the actual outcome of the decision, how willing are you to accept the decision?", col.names = linebreak(c("Value", "N", "Percent")))%>% 
  kable_styling(latex_options = "HOLD_position") 

#save to file
kable(table, booktabs = TRUE, linesep = "", escape = F, caption = "When you think about the actual outcome of the decision, how willing are you to accept the decision?", col.names = linebreak(c("Value", "N", "Percent")))%>% 
  kable_styling(latex_options = "HOLD_position") %>% 
  cat(., file = here("output", "novig", "tbls", "html",  "tbl-novig-accept-dv.html"))
```
The mean score for the post treatment measure "When you think about the actual outcome of the decision, how willing are you to accept the decision?" is `r round(mean(d$accept, na.rm=T), digits=2)`, and the standard deviation is `r round(sd(d$accept, na.rm=T), digits=2)`.

### Trust in politicians
```{r 2042_trust}
table <- d %>% mutate(
   trust = case_when(trust == 1 ~ "No trust at all",
                      trust == 2 ~ "Low trust",
                      trust == 3 ~ "Some trust",
                      trust == 4 ~ "High trust",
                      trust == 5 ~ "Very high trust"),
    trust = lvls_reorder(factor(trust), c(3, 2 , 4, 1, 5))) %>% 
  group_by(trust) %>%
   summarize(N_obs = n()) %>% 
  mutate(Percent_obs = round(N_obs/(sum(N_obs))*100))

kable(table, booktabs = TRUE, linesep = "", escape = F, caption = "Based on what you saw in the video, how much confidence do you have in the politicians who made the decision?", col.names = linebreak(c("Value", "N", "Percent")))%>% 
  kable_styling(latex_options = "HOLD_position") 

#save to file
  kable(table, booktabs = TRUE, linesep = "", escape = F, caption = "Based on what you saw in the video, how much confidence do you have in the politicians who made the decision?", col.names = linebreak(c("Value", "N", "Percent")))%>% 
  kable_styling(latex_options = "HOLD_position") %>% 
  cat(., file = here("output", "novig", "tbls", "html",  "tbl-novig-trust-dv.html"))
```
The mean score for the post treatment measure "Based on what you saw in the video, how much confidence do you have in the politicians who made the decision?" is `r round(mean(d$trust, na.rm=T), digits=2)`, and the standard deviation is `r round(sd(d$trust, na.rm=T), digits=2)`.

### Recording check
```{r 2043_recording}
table <- d %>%
  mutate(video_report = case_when(video_report == 1 ~ 'I had both sound and images',
                                      video_report == 2 ~ 'I had sound, but no images',
                                      video_report == 3 ~ 'I had images, but no sound',
                                      video_report == 4 ~ 'I had neither sound nor images',
                                      video_report == 5 ~ 'Something else prevented me from playing the video')) %>% 
  group_by(video_report) %>%
   summarize(N_obs = n()) %>% 
  mutate(Percent_obs = round(N_obs/(sum(N_obs))*100))

kable(table, booktabs = TRUE, linesep = "", escape = F, caption = "What was the recording like?", col.names = linebreak(c("Value", "N", "Percent"))) %>% 
  kable_styling(latex_options = "HOLD_position") %>% 
  footnote(general = 'Those who report they had both sound and images or had images but not sound were included in the main analysis. (The video was subtitled.)' )

#save to file
kable(table, booktabs = TRUE, linesep = "", escape = F, caption = "What was the recording like?", col.names = linebreak(c("Value", "N", "Percent"))) %>% 
  kable_styling(latex_options = "HOLD_position") %>% 
  footnote(general = 'Sample: All respondents who were given an unfavorable outcome. Those who report they had both sound and images or had images but not sound were included in the main analysis. (The video was subtitled.)' ) %>% 
  cat(., file = here("output", "novig", "tbls", "html",  "tbl-novig-videoreport.html"))
```

### Manipulation check
```{r 2044_mcheck}
table <- d %>%
  mutate(mcheck_favorability = case_when(
    favorability=="Favorable" & check_outcome==1 ~ "Correct",
    favorability=="Unfavorable" & check_outcome==2 ~ "Correct",
    favorability=="Favorable" & check_outcome==2 ~ "Incorrect",
    favorability=="Unfavorable" & check_outcome==1 ~ "Incorrect",
    check_outcome == 3 ~ 'Do not remember',
    check_outcome == 4 ~ 'Do not know' )) %>% 
  group_by(mcheck_favorability) %>%
   summarize(N_obs = n()) %>%
  mutate(Percent_obs = round(N_obs/(sum(N_obs))*100))
  
kable(table, booktabs = TRUE, linesep = "", escape = F, caption = "Proportion that correctly or incorrectly identify whether or not the decision outcome was in line with their own preferences. Sample includes respondents who did not see the video properly.", col.names = linebreak(c("Value", "N", "Percent"))) %>%
  kable_styling(latex_options = "HOLD_position")

#save to file
kable(table, booktabs = TRUE, linesep = "", escape = F, caption = "Proportion that correctly or incorrectly identify whether or not the decision outcome was in line with their own preferences.", col.names = linebreak(c("Value", "N", "Percent"))) %>%
  kable_styling(latex_options = "HOLD_position") %>%
  cat(., file = here("output", "novig", "tbls", "html",  "tbl-novig-mcheckfavorability.html"))

```

\newpage
## Effects on losers

The experiment was designed with a main interest on the reactions of the losers.
Four out of five respondents were therefore assigned to an outcome with an unfavorable outcome.
As described in the section on the experimental design, the last fifth of the respondents were assigned to a winning condition that was similar in text to the control condition for the losers. 
Thus, the winners were not exposed to any of the good loser messages.
Unless otherwise stated, the analyses are performed on the ITT (intention to treat) sample on the losers.

```{r 2050_prepare}

#Filter on respondents who receive an unfavorable outcome
d <- d %>% #ITT object
  filter(favorability == "Unfavorable") %>% 
  mutate(treatment = lvls_reorder(treatment, c(3, 2, 1, 4))) #Reorder appearance of treatment levels
e <- e %>% # Object with respondents filtered according to preregistered criteria
  filter(favorability == "Unfavorable") %>% 
  mutate(treatment = lvls_reorder(treatment, c(3, 2, 1, 4)))
f <- f %>% # Object with respondents who pass the manipulation check
  filter(favorability == "Unfavorable") %>% 
  mutate(treatment = lvls_reorder(treatment, c(3, 2, 1, 4)))
``` 
### Fairness 
#### Fairness - Figure 3

> Figure 3 in the manuscript:

```{r 20510_fairness}
fig <- d %>% 
  ggplot(aes(x = treatment, y = fairness)) +
  stat_summary(fun.data = mean_cl_normal, geom = 'point') +
  stat_summary(fun.data = mean_cl_normal, geom = 'linerange') +
  scale_y_continuous(limits = c(1, 5),
                     breaks = 1:5, 
                     labels = c('1 Not fair at all', '2', '3', '4', '5 Very fair')) +
  labs(x = " ",
       y = "",
       title = "", #Treatment groups and mean fairness perceptions of decision, Study 2
       subtitle = '', #Sample: Respondents who receive an unfavorable outcome.
       caption = '') + #Error bars represent 95% confidence intervals.
  theme_bw() +
  coord_flip()
fig

ggsave("figure3-exp2-fairness-losers.png",
  plot = fig,
  width = 6.0, height = 2.75, dpi = 600
)

#Table
res_main <-  lm_robust(fairness ~ treatment, data = d)
res_main <- broom::tidy(res_main)

labels <- data.frame(
  term = c(
    "treatmentLamenting politician",
    "treatmentSpecific prime",
    "treatmentGeneral Prime"

  ),
  label = c( "Lamenting politician",
             "Specific good loser message",
             "Generic good loser message")
)

table <- res_main %>%
  select(term, estimate, std.error, statistic, p.value) %>%
  mutate(term = case_when( term == "(Intercept)" ~ "Not shown (Intercept)",
                    term == "treatmentLamenting politician" ~ "Lamenting politician",
                   term == "treatmentGeneral Prime" ~ "Generic good loser message",
                   term == "treatmentSpecific prime" ~ "Specific good loser message"))

kable(table, booktabs = TRUE, caption = "Treatment effects among losers on fairness perceptions of decision, Study 2", col.names = linebreak(c("Treatment value", "Estimate", "Std. Error", "t-statistic", "p value")), digits = 2) %>%
  kable_styling(bootstrap_options = c("striped", "hover", "responsive"))

#save to file
kable(table, booktabs = TRUE, caption = "Treatment effects among losers on fairness perceptions of decision, Study 2", col.names = linebreak(c("Treatment value", "Estimate", "Std. Error", "t-statistic", "p value")), digits = 2) %>%
  kable_styling(bootstrap_options = c("striped", "hover", "responsive"))  %>%
  cat(., file = here("output", "novig", "tbls", "html",  "tbl-losers-fairness-novig.html"))
```
#### Fairness - including covariates
```{r 20511_fairness_covariates}
# Regression including covariates. Linear regression with heteroscedasticity-consistent standard errors using the estimatr package
res_main <-  lm_robust(fairness ~ treatment + polint + as.factor(age) + gender + opinion_strength_2 + imp_accept_2 + other_accept_2 + self_accept_2, data = d)
res_main <- broom::tidy(res_main)

#Table

table <- res_main %>%
  select(term, estimate, std.error, statistic, p.value) %>%
  mutate(term = case_when( term == "(Intercept)" ~ "Not shown",
                    term == "treatmentLamenting politician" ~ "Lamenting politician",
                   term == "treatmentGeneral Prime" ~ "Generic good loser message",
                   term == "treatmentSpecific prime" ~ "Specific good loser message",
                   term == 'polint' ~ 'Political interest',
                   term == 'as.factor(age)2' ~ 'Born between 1960 and 1989',
                   term == 'as.factor(age)3' ~ 'Born 1990 or later',
                   term == 'gender' ~ 'Gender',
                   term == 'opinion_strength_2Not important' ~ 'Issue not important',
                   term == 'imp_accept_2Not important' ~ 'Not important to accept democratic decisions',
                   term == 'other_accept_2Low degree' ~ 'Do not believe others accept democratic decisions',
                   term == 'self_accept_2Low degree' ~ 'Do not believe oneself accepts democratic decisions')
         )

kable(table, booktabs = TRUE, caption = "Treatment effects on fairness perceptions of decision, Study 1. Including covariates.", col.names = linebreak(c("Treatment value", "Estimate", "Std. Error", "t-statistic", "p value")), digits = 2) %>%
  kable_styling(bootstrap_options = c("striped", "hover", "responsive")) %>%     
  footnote('Political interest from 1 (lowest) to 5 (highest); Age in three categories with birth year before 1960 as reference category; gender as dichotomous variable where 0 is male and 1 is female; Issue importance and good loser norms recoded into dichotomous categories.' ) 

#save to file
kable(table, booktabs = TRUE, caption = "Treatment effects on fairness perceptions of decision, Study 1. Including covariates.", col.names = linebreak(c("Treatment value", "Estimate", "Std. Error", "t-statistic", "p value")), digits = 2) %>%
  kable_styling(bootstrap_options = c("striped", "hover", "responsive")) %>%
    footnote('Political interest from 1 (lowest) to 5 (highest); Age in three categories; gender as dichotomous variable where 0 is male and 1 is female; Issue importance and good loser norms recoded into dichotomous categories.' ) %>% 
  cat(., file = here("output", "novig", "tbls", "html",  "tbl-losers-fairness-novig-covariates.html"))
```

#### Fairness - with sample filtered on preregistered exclusion criteria

```{r 20512_fairness_treated}
fig <- e %>% 
  ggplot(aes(x = treatment, y = fairness)) +
  stat_summary(fun.data = mean_cl_normal, geom = 'point') +
  stat_summary(fun.data = mean_cl_normal, geom = 'linerange') +
  scale_y_continuous(limits = c(1, 5),
                     breaks = 1:5, 
                     labels = c('1 Not fair at all', '2', '3', '4', '5 Very fair')) +
  labs(x = " ",
       y = "",
       title = "Treatment groups and mean fairness perceptions of decision, Study 2",
       subtitle = 'Sample: Respondents who pass preregistered exclusion criteria.',
       caption = 'Error bars represent 95% confidence intervals.') +
  theme_bw() +
  coord_flip()
fig

ggsave("exp2-fairness-losers-treated.png",
  plot = fig,
  width = 5.5, height = 2.75
)

#Table
res_main <-  lm_robust(fairness ~ treatment, data = e)
res_main <- broom::tidy(res_main)

labels <- data.frame(
  term = c(
    "treatmentLamenting politician",
    "treatmentSpecific prime",
    "treatmentGeneral Prime"

  ),
  label = c( "Lamenting politician",
             "Specific good loser message",
             "Generic good loser message")
)

table <- res_main %>%
  select(term, estimate, std.error, statistic, p.value) %>%
  mutate(term = case_when( term == "(Intercept)" ~ "Not shown (Intercept)",
                    term == "treatmentLamenting politician" ~ "Lamenting politician",
                   term == "treatmentGeneral Prime" ~ "Generic good loser message",
                   term == "treatmentSpecific prime" ~ "Specific good loser message"))

kable(table, booktabs = TRUE, caption = "Treatment effects among losers on fairness perceptions of decision, Study 2", col.names = linebreak(c("Treatment value", "Estimate", "Std. Error", "t-statistic", "p value")), digits = 2) %>%
  kable_styling(bootstrap_options = c("striped", "hover", "responsive"))

#save to file
kable(table, booktabs = TRUE, caption = "Treatment effects among losers on fairness perceptions of decision, Study 2", col.names = linebreak(c("Treatment value", "Estimate", "Std. Error", "t-statistic", "p value")), digits = 2) %>%
  kable_styling(bootstrap_options = c("striped", "hover", "responsive"))  %>%
  cat(., file = here("output", "novig", "tbls", "html",  "tbl-losers-fairness-ntreated-ovig.html"))
```

#### Fairness - with sample filtered on preregistered exclusion criteria

```{r 20512_fairness_mcheck}
fig <- f %>% 
  ggplot(aes(x = treatment, y = fairness)) +
  stat_summary(fun.data = mean_cl_normal, geom = 'point') +
  stat_summary(fun.data = mean_cl_normal, geom = 'linerange') +
  scale_y_continuous(limits = c(1, 5),
                     breaks = 1:5, 
                     labels = c('1 Not fair at all', '2', '3', '4', '5 Very fair')) +
  labs(x = " ",
       y = "",
       title = "Treatment groups and mean fairness perceptions of decision, Study 2",
       subtitle = 'Sample: Respondents who pass preregistered exclusion criteria.',
       caption = 'Error bars represent 95% confidence intervals.') +
  theme_bw() +
  coord_flip()
fig

ggsave("exp2-fairness-losers-mcheck.png",
  plot = fig,
  width = 5.5, height = 2.75
)

#Table
res_main <-  lm_robust(fairness ~ treatment, data = f)
res_main <- broom::tidy(res_main)

labels <- data.frame(
  term = c(
    "treatmentLamenting politician",
    "treatmentSpecific prime",
    "treatmentGeneral Prime"

  ),
  label = c( "Lamenting politician",
             "Specific good loser message",
             "Generic good loser message")
)

table <- res_main %>%
  select(term, estimate, std.error, statistic, p.value) %>%
  mutate(term = case_when( term == "(Intercept)" ~ "Not shown (Intercept)",
                    term == "treatmentLamenting politician" ~ "Lamenting politician",
                   term == "treatmentGeneral Prime" ~ "Generic good loser message",
                   term == "treatmentSpecific prime" ~ "Specific good loser message"))

kable(table, booktabs = TRUE, caption = "Treatment effects among losers on fairness perceptions of decision, Study 2", col.names = linebreak(c("Treatment value", "Estimate", "Std. Error", "t-statistic", "p value")), digits = 2) %>%
  kable_styling(bootstrap_options = c("striped", "hover", "responsive"))

#save to file
kable(table, booktabs = TRUE, caption = "Treatment effects among losers on fairness perceptions of decision, Study 2", col.names = linebreak(c("Treatment value", "Estimate", "Std. Error", "t-statistic", "p value")), digits = 2) %>%
  kable_styling(bootstrap_options = c("striped", "hover", "responsive"))  %>%
  cat(., file = here("output", "novig", "tbls", "html",  "tbl-losers-fairness-mcheck-novig.html"))
```


#### Fairness moderated by issue importance

Whereas the table above shows that issue importance is associated with higher fairness perceptions of the decision, the figures below display that issue importance does not moderate the effect of the good loser messages.

```{r 20513_importance_treatment_fairness, fig.height=6}

res <-  lm_robust(fairness ~ factor(treatment)*opinion_strength, data = d) 

fig1 <- summary(margins(res, at = list(opinion_strength = 1:5)))  %>% 
  filter(factor == 'treatmentGeneral Prime') %>% 
    ggplot(aes(x = AME, y = opinion_strength,
               xmin = AME - (2 * SE) ,
               xmax = AME + (2 * SE))) +
  coord_flip() +
   geom_errorbarh(height = 0) +
  geom_point() +
  geom_vline(aes(xintercept = 0), linetype = "dotted") +
  scale_x_continuous(limits = c(-1, 2),
                     breaks = round(seq(-1, 2, 0.5), 1),
                     expand = c(0, 0)) +
  scale_y_continuous(limits = c(0.5, 5.5),
                     breaks = round(seq(-1, 5, 1), 1),
                     expand = c(0, 0)) +
  
  labs(x = 'AME',
       y = "",
       title = "Generic good loser message") +
  theme_bw() +
 # theme(plot.title = element_text(size=9), plot.subtitle = element_text(size=8), plot.margin = unit(c(2, 2, 2, 2), "mm"), axis.text.x=element_text(size=rel(0.7))) +
  theme(panel.spacing = unit(0.5, "lines"))

ggsave("exp2-fairness-importance-int-generalprime-losers.png",
  plot = fig1,
  width = 7, height = 2.75
)

fig2 <- summary(margins(res, at = list(opinion_strength = 1:5)))  %>% 
  filter(factor == 'treatmentSpecific prime') %>% 
    ggplot(aes(x = AME, y = opinion_strength,
               xmin = AME - (2 * SE) ,
               xmax = AME + (2 * SE))) +
  coord_flip() +
   geom_errorbarh(height = 0) +
  geom_point() +
  geom_vline(aes(xintercept = 0), linetype = "dotted") +
  scale_x_continuous(limits = c(-1, 2),
                     breaks = round(seq(-1, 2, 0.5), 1),
                     expand = c(0, 0)) +
  scale_y_continuous(limits = c(0.5, 5.5),
                     breaks = round(seq(-1, 5, 1), 1),
                     expand = c(0, 0)) +
  
  labs(x = 'AME',
       y = "",
       title = "Specific good loser message") +
  theme_bw() +
  #theme(plot.title = element_text(size=9), plot.subtitle = element_text(size=8), plot.margin = unit(c(2, 2, 2, 2), "mm"), axis.text.x=element_text(size=rel(0.7))) +
  theme(panel.spacing = unit(0.5, "lines"))

ggsave("exp2-fairness-importance-int-specificprime-losers.png",
  plot = fig2,
  width = 7, height = 2.75
)

fig3 <- summary(margins(res, at = list(opinion_strength = 1:5)))  %>% 
  filter(factor == 'treatmentLamenting politician') %>% 
    ggplot(aes(x = AME, y = opinion_strength,
               xmin = AME - (2 * SE) ,
               xmax = AME + (2 * SE))) +
  coord_flip() +
   geom_errorbarh(height = 0) +
  geom_point() +
  geom_vline(aes(xintercept = 0), linetype = "dotted") +
  scale_x_continuous(limits = c(-1, 2),
                     breaks = round(seq(-1, 2, 0.5), 1),
                     expand = c(0, 0)) +
  scale_y_continuous(limits = c(0.5, 5.5),
                     breaks = round(seq(-1, 5, 1), 1),
                     expand = c(0, 0)) +
  
  labs(x = 'AME',
       y = "Importance attached to issue of ban on begging, from 1 (low) to 5 (high)",
       title = "Lamenting politician.") +
  theme_bw() +
  #theme(plot.title = element_text(size=9), plot.subtitle = element_text(size=8), plot.margin = unit(c(2, 2, 2, 2), "mm"), axis.text.x=element_text(size=rel(0.7))) +
  theme(panel.spacing = unit(0.5, "lines"))

ggsave("exp2-fairness-importance-int-lamenting-losers.png",
  plot = fig3,
  width = 7, height = 2.75
)

ggsave("exp2-fairness-importance-int-lamenting-losers.pdf",
  plot = fig3,
  width = 7, height = 2.75
)

patchwork <- fig1 / fig2 / fig3
patchwork + plot_annotation(title = 'Moderating effects of issue importance on experimental treatment, Study 2', 
                            subtitle = 'Fairness perception of decision.')
#table
table <- summary(margins(res, at = list(opinion_strength = 1:5))) %>%
  filter(factor == 'treatmentGeneral Prime' | factor == 'treatmentLamenting politician' | factor == 'treatmentSpecific prime') %>% 
  mutate(factor = case_when(
  factor == 'opinion_strength' ~ 'Issue importance',
  factor == 'treatmentGeneral Prime' ~ 'Generic good loser message',
  factor == 'treatmentSpecific prime' ~ 'Specific good loser message', 
  factor == 'treatmentLamenting politician' ~ 'Lamenting politician')) 

kable(table, booktabs = TRUE, caption = "Moderating effects of issue importance on experimental treatment, Study 2", digits = 2, col.names = linebreak(c("Factor", 'Issue importance', "AME", "SE", "z-statistic", "p value", 'Lower', 'Upper'))) %>% 
  kable_styling(latex_options = "HOLD_position")   %>%
  collapse_rows(columns = 'Factor', valign = 'top') %>% 
  footnote(general = 'Sample: Respondents with unfavorable outcome.')

#save to file
kable(table, booktabs = TRUE, caption = "Moderating effects of issue importance on experimental treatment, Study 2", digits = 2, col.names = linebreak(c("Factor", 'Issue importance', "AME", "SE", "z-statistic", "p value", 'Lower', 'Upper'))) %>% 
  kable_styling(latex_options = "HOLD_position")   %>% 
  footnote(general = 'Sample: Respondents with unfavorable outcome.') %>% 
  cat(., file = here("output", "novig", "tbls", "html", "tbl-exp2-fairness-importance-int-losers.html"))
```

#### Fairness moderated by good loser norm
Similarly, whereas the table above shows that opinions about the importance of accepting democratic decisions is associated with higher fairness perceptions of the decision, the figures below display that it does not moderate the effect of the good loser messages.
```{r 20514_norm_treatment_fairness, fig.height=6}

res <-  lm(fairness ~ factor(treatment)*imp_accept, data = d) 

fig1 <- summary(margins(res, at = list(imp_accept = 1:5)))  %>% 
  filter(factor == 'treatmentGeneral Prime') %>% 
    ggplot(aes(x = AME, y = imp_accept,
               xmin = AME - (2 * SE) ,
               xmax = AME + (2 * SE))) +
  coord_flip() +
   geom_errorbarh(height = 0) +
  geom_point() +
  geom_vline(aes(xintercept = 0), linetype = "dotted") +
  scale_x_continuous(limits = c(-1, 2),
                     breaks = round(seq(-1, 2, 0.5), 1),
                     expand = c(0, 0)) +
  scale_y_continuous(limits = c(0.5, 5.5),
                     breaks = round(seq(-1, 5, 1), 1),
                     expand = c(0, 0)) +
  
  labs(x = 'AME',
       y = "",
       title = "Generic good loser message") +
  theme_bw() +
  theme(panel.spacing = unit(0.5, "lines"))

ggsave("exp2-accept-norm-int-generalprime-losers.png",
  plot = fig,
  width = 7, height = 2.75
)


fig2 <- summary(margins(res, at = list(imp_accept = 1:5)))  %>% 
  filter(factor == 'treatmentSpecific prime') %>% 
    ggplot(aes(x = AME, y = imp_accept,
               xmin = AME - (2 * SE) ,
               xmax = AME + (2 * SE))) +
  coord_flip() +
   geom_errorbarh(height = 0) +
  geom_point() +
  geom_vline(aes(xintercept = 0), linetype = "dotted") +
  scale_x_continuous(limits = c(-1, 2),
                     breaks = round(seq(-1, 2, 0.5), 1),
                     expand = c(0, 0)) +
  scale_y_continuous(limits = c(0.5, 5.5),
                     breaks = round(seq(-1, 5, 1), 1),
                     expand = c(0, 0)) +
  
  labs(x = 'AME',
       y = "",
       title = "Specific good loser message") +
  theme_bw() +
   theme(panel.spacing = unit(0.5, "lines"))

ggsave("exp2-accept-norm-int-specificprime-losers.png",
  plot = fig,
  width = 7, height = 2.75
)

fig3 <- summary(margins(res, at = list(imp_accept = 1:5)))  %>% 
  filter(factor == 'treatmentLamenting politician') %>% 
    ggplot(aes(x = AME, y = imp_accept,
               xmin = AME - (2 * SE) ,
               xmax = AME + (2 * SE))) +
  coord_flip() +
   geom_errorbarh(height = 0) +
  geom_point() +
  geom_vline(aes(xintercept = 0), linetype = "dotted") +
  scale_x_continuous(limits = c(-1, 2),
                     breaks = round(seq(-1, 2, 0.5), 1),
                     expand = c(0, 0)) +
  scale_y_continuous(limits = c(0.5, 5.5),
                     breaks = round(seq(-1, 5, 1), 1),
                     expand = c(0, 0)) +
  
  labs(x = 'AME',
       y = "Importance attached to accepting democratic decisions, from 1 (low) to 5 (high)",
       title = "Lamenting politician.") +
  theme_bw() +
   theme(panel.spacing = unit(0.5, "lines"))

ggsave("exp2-fairness-norm-int-lamenting-losers.png",
  plot = fig,
  width = 7, height = 2.75
)

patchwork <- fig1 / fig2 / fig3
patchwork + plot_annotation(title = 'Moderating effects of good loser norm on experimental treatment, Study 2', 
                            subtitle = 'Fairness perception of decision.')
```

```{r 20515_norm_treatment_fairness}

table <- summary(margins(res, at = list(imp_accept = 1:5))) %>%
   filter(factor == 'treatmentGeneral Prime' | factor == 'treatmentLamenting politician' | factor == 'treatmentSpecific prime') %>% 
  mutate(factor = case_when(
  factor == 'imp_accept' ~ 'Norm importance',
  factor == 'treatmentGeneral Prime' ~ 'Generic good loser message',
    factor == 'treatmentSpecific prime' ~ 'Specific good loser message',
  factor == 'treatmentLamenting politician' ~ 'Lamenting politician')) %>% 
  rename('Norm importance' = 'imp_accept')

kable(table, booktabs = TRUE, caption = "Moderating effects of norm importance on experimental treatment, Study 2", digits = 2, col.names = linebreak(c("Factor", 'Norm importance', "AME", "SE", "z-statistic", "p value", 'Lower', 'Upper'))) %>% 
  kable_styling(latex_options = "HOLD_position")   %>% 
  footnote(general = 'Sample: Respondents with unfavorable outcome.')
#save to file
kable(table, booktabs = TRUE, caption = "Moderating effects of norm importance on experimental treatment, Study 2", digits = 2, col.names = linebreak(c("Factor", 'Norm importance', "AME", "SE", "z-statistic", "p value", 'Lower', 'Upper'))) %>% 
  kable_styling(latex_options = "HOLD_position")   %>% 
  footnote(general = 'Sample: Respondents with unfavorable outcome.') %>% 
  cat(., file = here("output", "novig", "tbls", "html", "tbl-exp2-fairness-norm-int-losers.html"))
```
#### Fairness - with sample of respondents who pass manipulation check
```{r 20516_fairness_mcheck}
fig <- f %>% 
  ggplot(aes(x = treatment, y = fairness)) +
  stat_summary(fun.data = mean_cl_normal, geom = 'point') +
  stat_summary(fun.data = mean_cl_normal, geom = 'linerange') +
  scale_y_continuous(limits = c(1, 5),
                     breaks = 1:5, 
                     labels = c('1 Not fair at all', '2', '3', '4', '5 Very fair')) +
  labs(x = " ",
       y = "",
       title = "Treatment groups and mean fairness perceptions of decision, Study 2",
       subtitle = 'Sample: Respondents who pass manipulation check.',
       caption = 'Error bars represent 95% confidence intervals.') +
  theme_bw() +
  coord_flip()
fig

ggsave("exp2-fairness-mainfig-mcheck.png",
  plot = fig,
  width = 5.5, height = 2.75
)

#Table
res_main <-  lm_robust(fairness ~ treatment, data = f) 
res_main <- broom::tidy(res_main)

labels <- data.frame(
  term = c(
    "treatmentLamenting politician",
    "treatmentGeneral Prime",
    "treatmentSpecific prime"
  ),
  label = c( "Lamenting politician",
             "Generic good loser message",
             "Specific good loser message")
)
table <- res_main %>%
  filter(term != 'treatmentWinner') %>% 
  select(term, estimate, std.error, statistic, p.value) %>% 
  mutate(term = case_when( term == "(Intercept)" ~ "Not shown (Intercept)",
                    term == "treatmentLamenting politician" ~ "Lamenting politician",
                   term == "treatmentGeneral Prime" ~ "Generic good loser message", 
                   term == "treatmentSpecific prime" ~ "Specific good loser message"))

kable(table, booktabs = TRUE, caption = "Treatment effects on fairness perceptions of decision, Study 2. Sample: Respondents who pass manipulation check", col.names = linebreak(c("Treatment value", "Estimate", "Std. Error", "t-statistic", "p value")), digits = 2) %>% 
  kable_styling(bootstrap_options = c("striped", "hover", "responsive"))

kable(table, booktabs = TRUE, caption = "Treatment effects on fairness perceptions of decision, Study 2. Sample: Respondents who pass manipulation check", col.names = linebreak(c("Treatment value", "Estimate", "Std. Error", "t-statistic", "p value")), digits = 2) %>% 
  kable_styling(bootstrap_options = c("striped", "hover", "responsive")) %>% 
  cat(., file = here("output", "novig", "tbls", "html",  "tbl-fairness-novig-mcheck.html"))
```

### Acceptance
```{r 20520_accept}
fig <- d %>% 
  ggplot(aes(x = treatment, y = accept)) +
  stat_summary(fun.data = mean_cl_normal, geom = 'point') +
  stat_summary(fun.data = mean_cl_normal, geom = 'linerange') +
  scale_y_continuous(limits = c(1, 5),
                     breaks = 1:5,
                     labels = c('1 Not willing at all', '2', '3', '4', '5 Very willing')) +
  labs(x = '',
       y = '',
       title = "Treatment effects on willingness to accept decision, Study 2",
       caption = 'Error bars represent 95% confidence intervals.') +
  theme_bw() +
  coord_flip()

ggsave("exp2-accept-losers.png",
  plot = fig,
  width = 7, height = 2.75
)

#Table
res_main <-  lm_robust(accept ~ treatment, data = d) 
res_main <- broom::tidy(res_main)

labels <- data.frame(
  term = c(
    "treatmentLamenting politician",
    "treatmentGeneral Prime",
    "treatmentSpecific prime"
  ),
  label = c( "Lamenting politician",
             "Generic good loser message",
             "Specific good loser message")
)

table <- res_main %>% 
  select(term, estimate, std.error, statistic, p.value) %>% 
  mutate(term = case_when( term == "(Intercept)" ~ "Not shown (Intercept)",
                    term == "treatmentLamenting politician" ~ "Lamenting politician",
                   term == "treatmentGeneral Prime" ~ "Generic good loser message", 
                   term == "treatmentSpecific prime" ~ "Specific good loser message"))

kable(table, booktabs = TRUE, caption = "Treatment effects among losers on willingness to accept decision, Study 2", col.names = linebreak(c("Treatment value", "Estimate", "Std. Error", "t-statistic", "p value")), digits = 2) %>% 
  kable_styling(bootstrap_options = c("striped", "hover", "responsive"))  

kable(table, booktabs = TRUE, caption = "Treatment effects among losers on willingness to accept decision, Study 2", col.names = linebreak(c("Treatment value", "Estimate", "Std. Error", "t-statistic", "p value")), digits = 2) %>% 
  kable_styling(bootstrap_options = c("striped", "hover", "responsive"))  %>% 
  cat(., file = here("output", "novig", "tbls", "html",  "tbl-losers-accept-novig.html"))
```

#### Acceptance among respondents filtered on preregistered exclusion criteria
```{r 20521_accept_treated}
fig <- e %>% 
  ggplot(aes(x = treatment, y = accept)) +
  stat_summary(fun.data = mean_cl_normal, geom = 'point') +
  stat_summary(fun.data = mean_cl_normal, geom = 'linerange') +
  scale_y_continuous(limits = c(1, 5),
                     breaks = 1:5,
                     labels = c('1 Not willing at all', '2', '3', '4', '5 Very willing')) +
  labs(x = '',
       y = '',
       title = "Treatment effects on willingness to accept decision, Study 2",
       subtitle = 'Sample: Respondents who properly see the video.',
       caption = 'Error bars represent 95% confidence intervals.') +
  theme_bw() +
  coord_flip()

ggsave("exp2-accept-losers-treated.png",
  plot = fig,
  width = 7, height = 2.75
)

#Table
res_main <-  lm_robust(accept ~ treatment, data = e) 
res_main <- broom::tidy(res_main)

labels <- data.frame(
  term = c(
    "treatmentLamenting politician",
    "treatmentGeneral Prime",
    "treatmentSpecific prime"
  ),
  label = c( "Lamenting politician",
             "Generic good loser message",
             "Specific good loser message")
)

table <- res_main %>% 
  select(term, estimate, std.error, statistic, p.value) %>% 
  mutate(term = case_when( term == "(Intercept)" ~ "Not shown (Intercept)",
                    term == "treatmentLamenting politician" ~ "Lamenting politician",
                   term == "treatmentGeneral Prime" ~ "Generic good loser message", 
                   term == "treatmentSpecific prime" ~ "Specific good loser message"))

kable(table, booktabs = TRUE, caption = "Treatment effects among losers on willingness to accept decision, Study 2", col.names = linebreak(c("Treatment value", "Estimate", "Std. Error", "t-statistic", "p value")), digits = 2) %>% 
  kable_styling(bootstrap_options = c("striped", "hover", "responsive"))  

kable(table, booktabs = TRUE, caption = "Treatment effects among losers on willingness to accept decision, Study 2", col.names = linebreak(c("Treatment value", "Estimate", "Std. Error", "t-statistic", "p value")), digits = 2) %>% 
  kable_styling(bootstrap_options = c("striped", "hover", "responsive"))  %>% 
  cat(., file = here("output", "novig", "tbls", "html",  "tbl-losers-accept-novig.html"))
```

#### Acceptance - sample of respondents who pass manipulation check
```{r 20522_accept_mcheck}
fig <- f %>% 
  ggplot(aes(x = treatment, y = accept)) +
  stat_summary(fun.data = mean_cl_normal, geom = 'point') +
  stat_summary(fun.data = mean_cl_normal, geom = 'linerange') +
  scale_y_continuous(limits = c(1, 5),
                     breaks = 1:5,
                     labels = c('1 Not willing at all', '2', '3', '4', '5 Very willing')) +
  labs(x = '',
       y = '',
       title = "Treatment effects on willingness to accept decision, Study 2",
       subtitle = 'Sample: Respondents who pass manipulation check.',
       caption = 'Error bars represent 95% confidence intervals.') +
  theme_bw() +
  coord_flip()

ggsave("exp2-accept-mainfig-mcheck.png",
  plot = fig,
  width = 7, height = 2.75
)

#Table
res_main <-  lm_robust(accept ~ treatment, data = f) 
res_main <- broom::tidy(res_main)

labels <- data.frame(
  term = c(
    "treatmentLamenting politician",
    "treatmentGeneral Prime",
    "treatmentSpecific prime"

  ),
  label = c( "Lamenting politician",
             "Generic good loser message",
             "Specific good loser message")
)

table <- res_main %>% 
  filter(term != 'treatmentWinner') %>% 
  select(term, estimate, std.error, statistic, p.value) %>% 
  mutate(term = case_when( term == "(Intercept)" ~ "Not shown (Intercept)",
                    term == "treatmentLamenting politician" ~ "Lamenting politician",
                   term == "treatmentGeneral Prime" ~ "Generic good loser message", 
                   term == "treatmentSpecific prime" ~ "Specific good loser message"))

kable(table, booktabs = TRUE, caption = "Treatment effects on willingness to accept decision, Study 2. Sample: Respondents who pass manipulation check.", col.names = linebreak(c("Treatment value", "Estimate", "Std. Error", "t-statistic", "p value")), digits = 2) %>% 
  kable_styling(bootstrap_options = c("striped", "hover", "responsive"))

kable(table, booktabs = TRUE, caption = "Treatment effects on willingness to accept decision, Study 2. Sample: Respondents who pass manipulation check.", col.names = linebreak(c("Treatment value", "Estimate", "Std. Error", "t-statistic", "p value")), digits = 2) %>% 
  kable_styling(bootstrap_options = c("striped", "hover", "responsive"))  %>% 
  cat(., file = here("output", "novig", "tbls", "html",  "tbl-accept-novig-mcheck.html"))
```

### Trust in politician
```{r 2053_post_trust}

fig <- d %>% 
  ggplot(aes(x = treatment, y = trust)) +
  stat_summary(fun.data = mean_cl_normal, geom = 'point') +
  stat_summary(fun.data = mean_cl_normal, geom = 'linerange') +
  scale_y_continuous(limits = c(1, 5),
                     breaks = 1:5,
                     labels = c('1 No trust at all', '2', '3', '4', '5 Very high trust')) +
  labs(x = '',
       y = '',
       title = "Treatment effects on trust in politicians, Study 2",
       caption = 'Error bars represent 95% confidence intervals.') +
  theme_bw() +
  coord_flip()

ggsave(
  here("output", "novig", "figs", "pngs", "exp2-trust-losers.png"),
  plot = fig,
  width = 5.5, height = 2.75
)

ggsave(
  here("output", "novig", "figs", "pdfs", "exp2-trust-losers.pdf"),
  plot = fig,
  width = 5.5, height = 2.75
)


#Table
res_main <-  lm_robust(trust ~ treatment, data = d) 
res_main <- broom::tidy(res_main)

labels <- data.frame(
  term = c(
    "treatmentLamenting politician",
    "treatmentGeneral Prime",
    "treatmentSpecific prime"
  ),
  label = c( "Lamenting politician",
             "Generic good loser message",
             "Specific good loser message")
)

table <- res_main %>% 
  select(term, estimate, std.error, statistic, p.value) %>% 
  mutate(term = case_when( term == "(Intercept)" ~ "Not shown (Intercept)",
                    term == "treatmentLamenting politician" ~ "Lamenting politician",
                   term == "treatmentGeneral Prime" ~ "Generic good loser message", 
                   term == "treatmentSpecific prime" ~ "Specific good loser message"))

kable(table, booktabs = TRUE, caption = "Treatment effects among losers on trust in politician, Study 2", col.names = linebreak(c("Treatment value", "Estimate", "Std. Error", "t-statistic", "p value")), digits = 2) %>% 
  kable_styling(bootstrap_options = c("striped", "hover", "responsive")) 

kable(table, booktabs = TRUE, caption = "Treatment effects among losers on trust in politician, Study 2", col.names = linebreak(c("Treatment value", "Estimate", "Std. Error", "t-statistic", "p value")), digits = 2) %>% 
  kable_styling(bootstrap_options = c("striped", "hover", "responsive"))  %>% 
  cat(., file = here("output", "novig", "tbls", "html",  "tbl-losers-trust-novig.html"))
```

\newpage
## Differential attrition check

```{r, 2054_attrition, include=TRUE}
d <- d %>% mutate(attr_fairness = case_when(is.na(fairness) ~ 1,
                                                    TRUE ~ 0),
                          attr_accept = case_when(is.na(accept) ~ 1,
                                                  TRUE ~ 0))
#Fairness
res_main <- lm_robust(attr_fairness ~ treatment, data = d)
res_main <- tidy(res_main)

table <- res_main %>%
  select(term, estimate, std.error, statistic, p.value) %>%
  mutate(term = case_when( term == "(Intercept)" ~ "Not shown (Intercept)",
                    term == "treatmentLamenting politician" ~ "Lamenting politician",
                   term == "treatmentGeneral Prime" ~ "Generic good loser message",
                   term == "treatmentSpecific prime" ~ "Specific good loser message"))

kable(table, booktabs = TRUE, caption = "Differential attrition across treatment conditions, Study 2. Fairness.", col.names = linebreak(c("Treatment value", "Estimate", "Std. Error", "t-statistic", "p value")), digits = 2) %>%
  kable_styling(bootstrap_options = c("striped", "hover", "responsive")) %>% 
  footnote(general = 'F-statistic: 0.515 on 4 and 1274 DF,  p-value: 0.725')

#save to file
kable(table, booktabs = TRUE, caption = "Differential attrition across treatment conditions, Study 2, Fairness.", col.names = linebreak(c("Treatment value", "Estimate", "Std. Error", "t-statistic", "p value")), digits = 2) %>%
  kable_styling(bootstrap_options = c("striped", "hover", "responsive"))  %>% 
  footnote(general = 'F-statistic: 0.515 on 4 and 1274 DF,  p-value: 0.725') %>%
    cat(., file = here("output", "novig", "tbls", "html",  "tbl-attrition-fairness-novig.html"))

#Willingness to accept
res_main <- lm_robust(attr_accept ~ treatment, data = d)
res_main <- tidy(res_main)

table <- res_main %>%
  select(term, estimate, std.error, statistic, p.value) %>%
  mutate(term = case_when( term == "(Intercept)" ~ "Not shown (Intercept)",
                    term == "treatmentLamenting politician" ~ "Lamenting politician",
                   term == "treatmentGeneral Prime" ~ "Generic good loser message",
                   term == "treatmentSpecific prime" ~ "Specific good loser message"))

kable(table, booktabs = TRUE, caption = "Differential attrition across treatment conditions, Study 2. Willingness to accept.", col.names = linebreak(c("Treatment value", "Estimate", "Std. Error", "t-statistic", "p value")), digits = 2) %>%
  kable_styling(bootstrap_options = c("striped", "hover", "responsive")) %>% 
  footnote(general = 'F-statistic: 0.457 on 4 and 1274 DF,  p-value: 0.767')

#save to file
kable(table, booktabs = TRUE, caption = "Differential attrition across treatment conditions, Study 2. Willingness to accept.", col.names = linebreak(c("Treatment value", "Estimate", "Std. Error", "t-statistic", "p value")), digits = 2) %>%
  kable_styling(bootstrap_options = c("striped", "hover", "responsive")) %>% 
  footnote(general = 'F-statistic: 0.457 on 4 and 1274 DF,  p-value: 0.767') %>%
  cat(., file = here("output", "novig", "tbls", "html",  "tbl-attrition-accept-novig.html"))
```

\newpage
# STUDY III

The third study was also run online on a representative sample of adult Norwegians. 
We conducted a conjoint experiment with a rating assignment embedded in the 2018 fall wave of the Norwegian Citizen Panel. 

```{r 3010_loadraw_ncp, eval=FALSE}
d_1 <- ncp_raw %>%
  select(responseid, 
         polint = r11pk1,
         gender = r13P1,
         age = r13P5_2,
         opinion_begging = r13pad1,    
         importance_begging = r13pad2,
         opinion_toll = r13pad3,
         importance_toll = r13pad4,
         messenger = r13pad5_avsender,
         issue = r13pad5_sak,
         outcome = r13pad5_utfall,
         winner = r13pad5_vinner,
         margin = r13pad5_vinnermargin,
         r13pad6_ran,
         fairness_a = r13pad6a,
         fairness_b = r13pad6b,
         reasonable_a = r13pad7a,
         reasonable_b = r13pad7b,
         accept_a = r13pad8a,
         accept_b = r13pad8b
         )  

# Load Time tracker data (separate data set that provides information about how long the respondents spent on answering the three post measure questions)
d_2 <- import(here("Data", "TimeTracker - runde 13.xlsx"))

d_2 <-  d_2 %>%
  select(responseid = responseID, 
         timeTracker2_R13PAD6A,
         timeTracker2_R13PAD6B
         )  %>% 
  gather(Scale_time, time, timeTracker2_R13PAD6A:timeTracker2_R13PAD6B) %>% 
  filter(!is.na(time))

#Merge data sets
d_all <- left_join(d_1, d_2, by= "responseid") %>% 
   filter(!is.na(time)) 

#Make NA the respondents with values 98 (Not asked) or 97 (No answer) for entire dataset. (Checked with command 'sum(is.na(Loser$video_timespent)) that no values on that variable has value 97 or 98)
d_all[d_all == 97] <- NA
d_all[d_all == 98] <- NA

#Save ITT data set
export(d_all, here('Data', 'Goodloser-exp3-itt.rds'))

#Exclude respondents who rush through the experiment, in line with preregistered protocol. Note: This filtering was decided not to be performed in order to keep an ITT sample. Comment out the mutate and filter commands to create the data set.
d <- d_all
# %>%  mutate(median = median(time, na.rm = TRUE)) %>% 
#   filter(time >= 0.25*median)

export(d, here("Data", "Goodloser-exp3.rds"))
```

```{r 3011_reload}
d <- import(here("Data", "Goodloser-exp3.rds"))
```
\newpage
## Pre-treatment measures
### Ban on begging - opinion
```{r 3020_begging}
table <- d %>% mutate(opinion_begging = case_when(opinion_begging == 1 ~ "In favor",
                               opinion_begging == 2 ~ "Oppose")) %>% 
  group_by(opinion_begging) %>%
   summarize(N_obs = n()) %>% 
  mutate(Percent_obs = round(N_obs/(sum(N_obs))*100)) %>%
  ungroup()

  kable(table, booktabs = TRUE, linesep = "", escape = F, caption = "What is your opinion on a ban on begging in your municipality?", col.names = linebreak(c("Value", "N", "Percent"))) %>% 
  kable_styling(latex_options = "HOLD_position")
  #save to file
  kable(table, booktabs = TRUE, linesep = "", escape = F, caption = "What is your opinion on a ban on begging in your municipality?", col.names = linebreak(c("Value", "N", "Percent"))) %>% 
  kable_styling(latex_options = "HOLD_position")%>% 
  cat(., file = here("output", "nocon", "tbls", "html",  "tbl-nocon-begging-preference.html"))
```

### Ban on begging - importance
```{r 3021_beggingimp}
table <- d %>% 
     mutate(importance_begging = case_when(importance_begging == 5 ~ "Not important at all",
                               importance_begging == 4 ~ "Slightly important",
                               importance_begging == 3 ~ "Somewhat important",
                               importance_begging == 2 ~ "Important",
                               importance_begging == 1 ~ "Very important"),
           importance_begging = lvls_reorder(factor(importance_begging), c(2, 3, 4, 1, 5))) %>% 
     group_by(importance_begging) %>%
   summarize(N_obs = n()) %>% 
  mutate(Percent_obs = round(N_obs/(sum(N_obs))*100)) 

kable(table, booktabs = TRUE, linesep = "", escape = F, caption = "How important is the issue of begging ban to you?", col.names = linebreak(c("Value", "N", "Percent"))) %>% 
  kable_styling(latex_options = "HOLD_position")
#save to file
kable(table, booktabs = TRUE, linesep = "", escape = F, caption = "How important is the issue of begging ban to you?", col.names = linebreak(c("Value", "N", "Percent"))) %>% 
  kable_styling(latex_options = "HOLD_position")%>% 
  cat(., file = here("output", "nocon", "tbls", "html",  "tbl-nocon-begging-importance.html"))
```
The mean score for the pre treatment measure "How important is the issue of begging ban to you?" is `r -(round(mean(d$importance_begging, na.rm=T), digits=2))+6`, and the standard deviation is `r round(sd(d$importance_begging, na.rm=T), digits=2)`.

### Toll on diesel cars - opinion
```{r 3022_tolls}
table <- d %>% mutate(opinion_toll = case_when(opinion_toll == 1 ~ "In favor",
                               opinion_toll == 2 ~ "Oppose")) %>% 
  group_by(opinion_toll) %>%
   summarize(N_obs = n()) %>% 
  mutate(Percent_obs = round(N_obs/(sum(N_obs))*100)) 

  kable(table, booktabs = TRUE, linesep = "", escape = F, caption = "What is your opinion on an increase in the tolls for diesel cars in your municipality?", col.names = linebreak(c("Value", "N", "Percent"))) %>% 
  kable_styling(latex_options = "HOLD_position")
  #save to file
  kable(table, booktabs = TRUE, linesep = "", escape = F, caption = "What is your opinion on an increase in the tolls for diesel cars in your municipality?", col.names = linebreak(c("Value", "N", "Percent"))) %>% 
  kable_styling(latex_options = "HOLD_position")%>% 
  cat(., file = here("output", "nocon", "tbls", "html",  "tbl-nocon-toll-preference.html"))
```

### Toll on diesel cars - importance
```{r 3023_tollsimp}
table <- d %>% mutate(importance_toll = case_when(importance_toll == 5 ~ "Not important at all",
                               importance_toll == 4 ~ "Slightly important",
                               importance_toll == 3 ~ "Somewhat important",
                               importance_toll == 2 ~ "Important",
                               importance_toll == 1 ~ "Very important"),
                        importance_toll = lvls_reorder(factor(importance_toll), c(2, 3, 4, 1, 5))) %>% 
  group_by(importance_toll) %>%
   summarize(N_obs = n()) %>% 
  mutate(Percent_obs = round(N_obs/(sum(N_obs))*100))

  kable(table, booktabs = TRUE, linesep = "", escape = F, caption = "How important is the issue of increased tolls for diesel cars to you?", col.names = linebreak(c("Value", "N", "Percent"))) %>% 
  kable_styling(latex_options = "HOLD_position") 
  #save to file
  kable(table, booktabs = TRUE, linesep = "", escape = F, caption = "How important is the issue of increased tolls for diesel cars to you?", col.names = linebreak(c("Value", "N", "Percent"))) %>% 
  kable_styling(latex_options = "HOLD_position") %>% 
  cat(., file = here("output", "nocon", "tbls", "html",  "tbl-nocon-toll-preference.html"))
```
The mean score for the pre treatment measure "How important is the issue of increased tolls for diesel cars to you?" is `r -(round(mean(d$importance_toll, na.rm=T), digits=2))+6`, and the standard deviation is `r round(sd(d$importance_toll, na.rm=T), digits=2)`.

\newpage
## Experimental vignette
```{r, 3030_vignette}
table <- tibble(Treatments = c("Issue", "Issue", "Outcome", "Outcome", "Winning margin", "Winning margin", "Winning margin", "Winner's gloating", "Winner's gloating", rep("Messenger and message", 7)), 
                Value = c("Ban on begging", 
                          "Diesel car road toll",
                          "Yes",
                          "No",
                          "Not shown",
                          "Small margin",
                          "Large margin", 
                          "Not shown", 
                          "Yes", 
                          "Not shown", 
                          "Politician, no message", 
                          "Politician,  specific good loser message",
                          "Politician, generic good loser message", 
                          "Newspaper, no message",
                          "Newspaper, specific good loser message", 
                          "Newspaper, generic good loser message"), 
                Text = c("in the future, begging on the streets will be banned or permitted in the municipality. This is a controversial decision. Some residents are strong in favour of a ban (the “Yes” side), while other residents are strongly against a ban (the “No” side). Some parties propose a ban on begging.",
                         "in the future, diesel cars will pay increased tolls. This is a controversial decision. Some residents are strongly in favour of such an increase (the “Yes” side), while others are strongly against an increase (the “No” side). Some parties propose such an increase in tolls for diesel cars.",
                         "The Yes side won the vote",
                         "The No side won the vote",
                         ".",
                         "with a slight majority.",
                         "with a large majority.",
                         " ",
                         "Following the decision, a politician on the winning side says that it was a good decision and that common sense prevailed.",
                         " ",
                         "The leader of one of the parties that was against the decision says that they are disappointed and that the decision was wrong.",
                         "The leader of one of the parties that was against the decision says that they are disappointed and that the decision was wrong,  but that it was a fair fight where both sides had the opportunity to argue in favour of their views.",
                         "The leader of one of the parties that was against the decision says that they are disappointed and that the decision was wrong,  but that is what living in a democracy is all about. Sometimes you win, sometimes you lose.",
                         "The local newspaper – which was against the decision – writes in an editorial that they are disappointed and that the decision was wrong.",
                         "The local newspaper – which was against the decision – writes in an editorial that they are disappointed and that the decision was wrong, but that it was a fair fight where both sides had the opportunity to argue in favour of their views.",
                         "The local newspaper – which was against the decision – writes in an editorial that they are disappointed and that the decision was wrong, but that is what living in a democracy is all about. Sometimes you win, sometimes you lose.")
)

 table %>% 
    mutate_all(linebreak) %>% 
    kable(booktabs = T, linesep = "", escape = F,  caption = "Vignette treatment dimensions and values", col.names = linebreak(c("Feature", "Level", "Text"))) %>% 
    collapse_rows(columns = 1, latex_hline = "major", valign = "top") %>% 
  kable_styling(latex_options = c("scale_down", "HOLD_position")) %>% 
   footnote(general = 'Experimental vignette (treatments in {curly brackets}): Below, we have described a hypothetical situation. Please read through the situation carefully and then answer the three questions that follow. Imagine that your municipality must decide on {Issue} The decision will be taken by the municipal council and follow the usual procedures. The proposal will initially be debated by the municipal council where all the members will have the opportunity to express their opinions and arguments regarding the issue. The debate will be public, and journalists will be in attendance to report on the debate. In the end, the politicians will vote on the issue. {Outcome} {[Winning margin} {Winner gloating} {Messenger and prime}') 
 
 #save to file
 table %>% 
    mutate_all(linebreak) %>% 
    kable(booktabs = T, linesep = "", escape = F,  caption = "Vignette treatment dimensions and values", col.names = linebreak(c("Preference", "Treatment", "Text"))) %>% 
    collapse_rows(columns = 1, latex_hline = "major", valign = "top") %>% 
  kable_styling(latex_options = c("scale_down", "HOLD_position")) %>% 
   footnote(general = 'Experimental vignette (treatments in {curly brackets}): Below, we have described a hypothetical situation. Please read through the situation carefully and then answer the three questions that follow. Imagine that your municipality must decide on {Issue} The decision will be taken by the municipal council and follow the usual procedures. The proposal will initially be debated by the municipal council where all the members will have the opportunity to express their opinions and arguments regarding the issue. The debate will be public, and journalists will be in attendance to report on the debate. In the end, the politicians will vote on the issue. {Outcome} {[Winning margin} {Winner gloating} {Messenger and prime}') %>% 
  cat(., file = here("output", "nocon", "tbls", "html",  "tbl-nocon-vignette.html"))
```

### Descriptive information about treatment groups

> We restrain the descriptives to the treatment dimension of main interest (democratic message)

```{r, 3031_balance}
#Gender
fig1 <- d %>% mutate(gender = as.numeric(gender)-1,
                      message = case_when(messenger == 1 ~ "Not shown",
                               messenger == 2  | messenger == 5 ~ "Lamenting politician",
                               messenger == 3  | messenger == 6 ~ "Specific message",
                               messenger == 4 | messenger == 7 ~ "Generic message"),
                     message = lvls_reorder(message, c(3, 2, 4, 1)) ) %>% 
  ggplot(aes(x = message, y = gender)) +
stat_summary(fun.data = mean_cl_normal, geom = 'linerange') +
  stat_summary(fun.data = mean_cl_normal, geom = 'point') +
   scale_y_discrete(limits = c(0,1),
                   breaks = seq(from = 0, to = 1, by = 0.2)) +
  labs(x = '',
       y = '',
       title = 'Gender',
       subtitle = 'Proportion Females') +
  coord_flip() +
  theme_bw()

#Save figure in png and pdf format
ggsave("exp3-balance-gender.png",
  plot = fig1,
  width = 7, height = 2.75
)

#Age
fig2 <- d %>% mutate(age = as.character(case_when(age == 1 ~ "<1960",
                                                  age == 2 ~ "1960-1989",
                                                  age == 3 ~ ">1989")),
                     age = lvls_reorder(age, c(1, 3, 2)),
                     message = case_when(messenger == 1 ~ 'Not shown',
                               messenger == 2  ~ "Lamenting \npolitician",
                               messenger == 3 ~ "Specific message",
                               messenger == 4  ~ "Generic message"),
                     message = lvls_reorder(message, c(3, 2, 4, 1))) %>% 
  filter(!is.na(message)) %>% 
  ggplot(aes(x = age)) +
  geom_bar(aes(y = (..count..)/sum(..count..))) + 
          scale_y_continuous(labels=scales::percent) +
    labs(x = '',
       y = '',
       title = 'Birth Year', 
       caption = 'Distributions w/ politician as messenger') +
  scale_x_discrete(guide = guide_axis(n.dodge = 2)) + 
  theme_bw() +
  facet_wrap(~message)

#Save figure in png and pdf format
ggsave("exp3-balance-age.png",
  plot = fig2,
  width = 7, height = 2.75
)

#Political interest
fig3 <- d %>% mutate(treatment = case_when(messenger == 1 ~ "Not shown",
                               messenger == 2  | messenger == 5 ~ "Lamenting politician",
                               messenger == 3  | messenger == 6 ~ "Specific good loser message",
                               messenger == 4 | messenger == 7 ~ "Generic good loser message")) %>% 
                       ggplot(aes(x = treatment, y = polint)) +
stat_summary(fun.data = mean_cl_normal, geom = 'linerange') +
  stat_summary(fun.data = mean_cl_normal, geom = 'point') +
  scale_y_continuous(limits = c(1,5),
                   labels = c('Not interested at all',
                              '',
                              '',
                              '',
                              'Very \ninterested')) +
  labs(x = '',
       y = '',
       title = "Political interest"
       ) +
theme_bw() +
  coord_flip()

#Save figure in png and pdf format
ggsave("exp3-balance-polint.png",
  plot = fig3,
  width = 7, height = 2.75
)

patchwork <- fig2 + fig1 / fig3
patchwork + plot_annotation(title = 'Descriptive information about treatment groups')

```

\newpage
## Post-treatment measures
Please note that the the respondents were randomly assigned to *either* a worded answer scale, *or* a numbered answer scale. 
This accounts for the high share of NA's in the post treatment distribution tables.

### Fairness
```{r 3040_fairness}
table <- d %>%  mutate(fairness_a = case_when(fairness_a == 1 ~ "Very fair",
                                fairness_a == 2 ~ "Fair",
                                fairness_a == 3 ~ "Somewhat fair",
                                fairness_a == 4 ~ "Slightly fair",
                                fairness_a == 5 ~ "Not fair at all"),
           fairness_a = lvls_reorder(factor(fairness_a), c(5, 1, 4, 3, 2))) %>% 
  group_by(fairness_a) %>%
   summarize(N_obs = n()) %>% 
  mutate(Percent_obs = round(N_obs/(sum(N_obs))*100)) 

  kable(table, booktabs = TRUE, linesep = "", escape = F, caption = "What do you think about the way the decision was made?", col.names = linebreak(c("Value", "N", "Percent"))) %>% 
    footnote(general = 'Original scale order. The order is reversed in subsequent analyses for ease of interpretation.') %>% 
  kable_styling(latex_options = "HOLD_position")  
#save to file
  kable(table, booktabs = TRUE, linesep = "", escape = F, caption = "What do you think about the way the decision was made?", col.names = linebreak(c("Value", "N", "Percent"))) %>% 
    footnote(general = 'Original scale order. The order is reversed in subsequent analyses for ease of interpretation.') %>% 
  kable_styling(latex_options = "HOLD_position") %>% 
  cat(., file = here("output", "nocon", "tbls", "html",  "tbl-nocon-eval-dv1.html"))

table <- d %>% mutate(fairness_b = case_when(fairness_b == 1 ~ "1 Most fair",
                                fairness_b == 2 ~ "2 ",
                                fairness_b == 3 ~ "3",
                                fairness_b == 4 ~ "4",
                                fairness_b == 5 ~ "5 Not fair")) %>% 
  group_by(fairness_b) %>%
   summarize(N_obs = n()) %>% 
  mutate(Percent_obs = round(N_obs/(sum(N_obs))*100))

 kable(table, booktabs = TRUE, linesep = "", escape = F, caption = "What do you think about the way the decision was made?", col.names = linebreak(c("Value", "N", "Percent"))) %>% 
   footnote(general = 'Original scale order. The order is reversed in subsequent analyses for ease of interpretation.') %>% 
  kable_styling(latex_options = "HOLD_position")
 #save to file
  kable(table, booktabs = TRUE, linesep = "", escape = F, caption = "What do you think about the way the decision was made?", col.names = linebreak(c("Value", "N", "Percent"))) %>% 
    footnote(general = 'Original scale order. The order is reversed in subsequent analyses for ease of interpretation.') %>% 
  kable_styling(latex_options = "HOLD_position") %>% 
  cat(., file = here("output", "nocon", "tbls", "html",  "tbl-nocon-eval-dv2.html"))
```
There is a clear difference in the distribution of responses depending upon which answer scale was offered to the respondents. 
In particular, answer options in the first and second rows differed substantially, where the numbered scale lead the respondents to more often give the most extreme response, while the most typical response on the worded scale was the secondmost extreme answer option.

The mean score for the pre treatment measure "What do you think about the way the decision was made?" is `r -(round(mean(d$fairness_a, na.rm=T),  digits=2))+6`, and the standard deviation is `r round(sd(d$fairness_a, na.rm=T), digits=2)` for the worded answer scale. 
For the numbered answer scale, the mean score is `r -(round(mean(d$fairness_b, na.rm=T), digits=2))+6`, and the standard deviation is `r round(sd(d$fairness_b, na.rm=T), digits=2)`

### Acceptance
``` {r 3041_accept}
table <- d %>% mutate( accept_a = case_when(accept_a == 1 ~ "Very willing",
                                accept_a == 2 ~ "Willing",
                                accept_a == 3 ~ "Somewhat willing",
                                accept_a == 4 ~ "Slightly willing",
                                accept_a == 5 ~ "Not willing at all"),
           accept_a = lvls_reorder(factor(accept_a), c(4, 5, 3, 2, 1))) %>% 
  group_by(accept_a) %>%
   summarize(N_obs = n()) %>% 
  mutate(Percent_obs = round(N_obs/(sum(N_obs))*100))

kable(table, booktabs = TRUE, linesep = "", escape = F, caption = "When you think about the actual outcome of the decision, how willing are you to accept the decision?", col.names = linebreak(c("Value", "N", "Percent"))) %>%  footnote(general = 'Original scale order. The order is reversed in subsequent analyses for ease of interpretation.') %>% 
  kable_styling(latex_options = "HOLD_position")

#save to file
   kable(table, booktabs = TRUE, linesep = "", escape = F, caption = "When you think about the actual outcome of the decision, how willing are you to accept the decision?", col.names = linebreak(c("Value", "N", "Percent"))) %>%   footnote(general = 'Original scale order. The order is reversed in subsequent analyses for ease of interpretation.') %>% 
     kable_styling(latex_options = "HOLD_position") %>% 
  cat(., file = here("output", "nocon", "tbls", "html",  "tbl-nocon-accept-dv1.html"))

table <- d %>% mutate(accept_b = case_when(accept_b == 1 ~ "1 Most willing",
                                accept_b == 2 ~ "2 ",
                                accept_b == 3 ~ "3",
                                accept_b == 4 ~ "4",
                                accept_b == 5 ~ "5 Not willing")) %>% 
  group_by(accept_b) %>%
   summarize(N_obs = n()) %>% 
  mutate(Percent_obs = round(N_obs/(sum(N_obs))*100)) 

  kable(table, booktabs = TRUE, linesep = "", escape = F, caption = "When you think about the actual outcome of the decision, how willing are you to accept the decision?", col.names = linebreak(c("Value", "N", "Percent"))) %>%  
    footnote(general = 'Original scale order. The order is reversed in subsequent analyses for ease of interpretation.') %>% 
    kable_styling(latex_options = "HOLD_position")
#save to file
  kable(table, booktabs = TRUE, linesep = "", escape = F, caption = "When you think about the actual outcome of the decision, how willing are you to accept the decision?", col.names = linebreak(c("Value", "N", "Percent"))) %>% 
    footnote(general = 'Original scale order. The order is reversed in subsequent analyses for ease of interpretation.') %>%   
    kable_styling(latex_options = "HOLD_position") %>% 
  cat(., file = here("output", "nocon", "tbls", "html",  "tbl-nocon-accept-dv2.html"))

```
There is a clear difference in the distribution of responses depending upon which answer scale was offered to the respondents. 
In particular, answer options in the first and second rows differed substantially, where the numbered scale lead the respondents to more often give the most extreme response, while the most typical response on the worded scale was the secondmost extreme answer option.
The mean score for the pre treatment measure "When you think about the actual outcome of the decision, how willing are you to accept the decision?" is `r -(round(mean(d$accept_a, na.rm=T), digits=2))+6`, and the standard deviation is `r round(sd(d$accept_a, na.rm=T), digits=2)` for the numbered answer scale.
For the worded answer scale, the mean score is `r -(round(mean(d$accept_b, na.rm=T), digits=2))+6`, and the standard deviation is `r round(sd(d$accept_b, na.rm=T), digits=2)`.


### Reasonable decision
```{r 3042_reasonable}
table <- d %>% mutate(reasonable_a = case_when(reasonable_a == 1 ~ "Very reasonable",
                                reasonable_a == 2 ~ "Reasonable",
                                reasonable_a == 3 ~ "Somewhat reasonable",
                                reasonable_a == 4 ~ "Slightly reasonable",
                                reasonable_a == 5 ~ "Not reasonable at all"),
           reasonable_a = lvls_reorder(factor(reasonable_a), c(5, 2, 4, 3, 1))) %>%
  group_by(reasonable_a) %>%
   summarize(N_obs = n()) %>%
  mutate(Percent_obs = round(N_obs/(sum(N_obs))*100))
#for bookdown
   kable(table, booktabs = TRUE, linesep = "", escape = F, caption = "How reasonable do you think the decision was?", col.names = linebreak(c("Value", "N", "Percent"))) %>%
      footnote(general = 'Original scale order. The order is reversed in subsequent analyses for ease of interpretation.') %>% 
  kable_styling(latex_options = "HOLD_position")
#save to file
   kable(table, booktabs = TRUE, linesep = "", escape = F, caption = "How reasonable do you think the decision was?", col.names = linebreak(c("Value", "N", "Percent"))) %>%
      footnote(general = 'Original scale order. The order is reversed in subsequent analyses for ease of interpretation.') %>% 
  kable_styling(latex_options = "HOLD_position") %>%
  cat(., file = here("output", "nocon", "tbls", "html",  "tbl-nocon-reasonable-dv1.html"))

table <- d %>% mutate( reasonable_b = case_when(reasonable_b == 1 ~ "5 Most reasonable",
                                reasonable_b == 2 ~ "4 ",
                                reasonable_b == 3 ~ "3",
                                reasonable_b == 4 ~ "2",
                                reasonable_b == 5 ~ "1 Not reasonable"),
                       reasonable_b = lvls_reorder(factor(reasonable_b), c(5, 4, 3, 2, 1))) %>%
  group_by(reasonable_b) %>%
   summarize(N_obs = n()) %>%
  mutate(Percent_obs = round(N_obs/(sum(N_obs))*100))
#for bookdown
  kable(table, booktabs = TRUE, linesep = "", escape = F, caption = "How reasonable do you think the decision was?", col.names = linebreak(c("Value", "N", "Percent"))) %>%
     footnote(general = 'Original scale order. The order is reversed in subsequent analyses for ease of interpretation.') %>% 
  kable_styling(latex_options = "HOLD_position")

#save to file
  kable(table, booktabs = TRUE, linesep = "", escape = F, caption = "How reasonable do you think the decision was?", col.names = linebreak(c("Value", "N", "Percent"))) %>%
     footnote(general = 'Original scale order. The order is reversed in subsequent analyses for ease of interpretation.') %>% 
  kable_styling(latex_options = "HOLD_position") %>%
  cat(., file = here("output", "nocon", "tbls", "html",  "tbl-nocon-reasonable-dv2.html"))
```
The mean score for the pre treatment measure asking how reasonable the decision was is `r -(round(mean(d$accept_a, na.rm=T), digits=2))+6`, and the standard deviation is `r round(sd(d$reasonable_a, na.rm=T), digits=2)` for the numbered answer scale.
The standard deviation is `r round(sd(d$reasonable_a, na.rm=T), digits=2)`.
For the worded answer scale, the mean score is `r -(round(mean(d$reasonable_b, na.rm=T), digits=2))+6`, and the standard deviation is `r round(sd(d$reasonable_b, na.rm=T), digits=2)`.

\newpage
## Effects on losers

```{r 3050_prepare}
#Prepare data 
main_01 <- d %>% 
  mutate(rsp_id = as.numeric(responseid),
         rsp_beg = case_when(opinion_begging == 1 ~ "In favour of ban on begging",
                             opinion_begging == 2 ~ "Against ban on begging"),
         rsp_beg_imp = case_when(importance_begging %in% 1:2 ~ "Important",
                                  importance_begging %in% 3:5 ~ "Not important"),
         rsp_toll = case_when(opinion_toll == 1 ~ "In favour of road toll increase of diesel cars",
                              opinion_toll == 2 ~ "Against road toll increase of diesel cars"),
         rsp_toll_imp = case_when(importance_toll %in% 1:2 ~ "Important",
                                  importance_toll %in% 3:5 ~ "Not important"),
         treat_outcome = case_when(outcome == 1 ~ "The Yes side won the vote",
                                 outcome == 2 ~ "The No side won the vote"),
         treat_outfav = case_when(issue == 1 & opinion_begging == 1 & outcome == 1 ~ "Favorable outcome",
                                  issue == 1 & opinion_begging == 2 & outcome == 2 ~ "Favorable outcome",
                                  issue == 1 & opinion_begging == 1 & outcome == 2 ~ "Unfavorable outcome",
                                  issue == 1 & opinion_begging == 2 & outcome == 1 ~ "Unfavorable outcome",
                                  issue == 2 & opinion_toll == 1 & outcome == 1 ~ "Favorable outcome",
                                  issue == 2 & opinion_toll == 2 & outcome == 2 ~ "Favorable outcome",
                                  issue == 2 & opinion_toll == 1 & outcome == 2 ~ "Unfavorable outcome",
                                  issue == 2 & opinion_toll == 2 & outcome == 1 ~ "Unfavorable outcome"),
         treat_issue = case_when(issue == 1 ~ "Ban on begging",
                               issue == 2 ~ "Road toll increase of diesel cars"),
         treat_winningmargin = case_when(margin == 1 ~ "Not shown",
                                       margin == 2 ~ "Slight majority",
                                       margin == 3 ~ "Large majority"),
         treat_winnergloat = case_when(winner == 1 ~ "Not shown",
                                     winner == 2 ~ "Winning politician gloats"),
        treat_message = case_when(messenger == 1 ~ "Not shown",
                               messenger == 2  | messenger == 5 ~ "Lamenting politician",
                               messenger == 3  | messenger == 6 ~ "Specific good loser message",
                               messenger == 4 | messenger == 7 ~ "Generic good loser message"),
         treat_messenger = case_when(messenger %in% 3:4 ~ "Political leader",
                                   messenger %in% 6:7 ~ "Local newspaper"),
        treat_scale = case_when(r13pad6_ran == 1 ~ "Worded",
                          r13pad6_ran == 2 ~ "Numbered"),
         post_fair = case_when(fairness_a == 1 | fairness_b == 1 ~ 5, #Reverse scales
                          fairness_a == 2 | fairness_b == 2 ~ 4,
                          fairness_a == 3 | fairness_b == 3 ~ 3,
                          fairness_a == 4 | fairness_b == 4 ~ 2,
                          fairness_a == 5 | fairness_b == 5 ~ 1),
          post_reasonable = case_when(reasonable_a == 1 | reasonable_b == 1 ~ 5,
                          reasonable_a == 2 | reasonable_b == 2 ~ 4,
                          reasonable_a == 3 | reasonable_b == 3 ~ 3,
                          reasonable_a == 4 | reasonable_b == 4 ~ 2,
                          reasonable_a == 5 | reasonable_b == 5 ~ 1),
          post_accept = case_when(accept_a == 1 | accept_b == 1 ~ 5,
                          accept_a == 2 | accept_b == 2 ~ 4,
                          accept_a == 3 | accept_b == 3 ~ 3,
                          accept_a == 4 | accept_b == 4 ~ 2,
                          accept_a == 5 | accept_b == 5 ~ 1)

  ) %>% 

 # replace_with_na_all(condition = ~.x == 98 )%>%  #Recode 98 (not asked) as missing
  filter(!is.na(r13pad6_ran)) %>%  #Remove respondents who did not receive the post measures
## We want the value labels in particular order for the tables and figures.
        mutate(treat_winningmargin = lvls_reorder(treat_winningmargin, c(2, 3, 1)), 
               treat_message = lvls_reorder(treat_message, c(3, 2, 4, 1)) 
        )


main_00 <- main_01

main_01 <- main_01 %>%   
      filter(treat_outfav == "Unfavorable outcome") %>% 
     pivot_longer(cols= c(contains('_imp')), names_to = 'variable', values_to = 'importance') %>% 
      filter(c(treat_issue == "Ban on begging" & variable == "rsp_beg_imp") | treat_issue == "Road toll increase of diesel cars" & variable == "rsp_toll_imp")
``` 

Unless otherwise stated, analyses in this section are concerned with experimental subjects who find the decision outcome to align unfavorably with their own preferences (N = `r main_01 %>% summarise(n())`)

### Fairness
#### Fairness - Figure 4

> Figure 4 in the manuscript: 

```{r 3051_fairness}

source("amce.R")

res_main <-  main_01 %>%
  amce(post_fair, treat_message) 

res_main <- res_main %>% 
  mutate(
  treatment =  case_when(
            treatment == "treat_message" ~ "Democratic\nmessage")
  )

#Figure
fig_amce <-
  res_main %>%
  ggplot(aes(x = estimate, y = value)) +
   geom_errorbarh(
    aes(xmin = estimate - (2 * std_error),
        xmax = estimate + (2 * std_error)),
    height = 0) +
  geom_point() +
  geom_vline(aes(xintercept = 0), linetype = "dotted") +
  scale_x_continuous(
    limits = c(-1, 1),
    breaks = round(seq(-1, 1, .2), 2),
    expand = c(0, 0)) +
    labs(
    x = "", #Marginal effect, fairness perception of decision
    y = "",
    title = '', #Average Marginal Component Effect -- Study 3
    subtitle = '') + #Sample: Respondents who received an unfavorable outcome
  theme_bw() +
  theme(plot.margin = unit(c(2, 2, 2, 2), "mm"),  plot.title = element_text(size=9), plot.subtitle = element_text(size=8), strip.text.y = element_text(size=6, angle=0) ,      axis.text.x=element_text(size=rel(0.7)))
fig_amce


ggsave("figure4-exp3-fairness-losers.png",
  plot = fig_amce,
  width = 6, height = 2.75, dpi = 600
)

#table
res_main <- res_main %>% 
  select(value, estimate, std_error, statistic, p_value)


kable(res_main, booktabs = TRUE, caption = "Average Marginal Component Effect -- Study 3", col.names = linebreak(c("Treatment value", "Estimate", "Std. Error", "t-statistic", "p value")), digits = 2) %>% 
  kable_styling(bootstrap_options = c("striped", "hover", "responsive"))

kable(res_main, booktabs = TRUE, caption = "Average Marginal Component Effect -- Study 3", col.names = linebreak(c("Treatment value", "Estimate", "Std. Error", "t-statistic", "p value")), digits = 2) %>% 
  kable_styling(bootstrap_options = c("striped", "hover", "responsive")) %>% 
  cat(., file = here("output", "nocon", "tbls", "html",  "tbl-fig4-losers-fairness-nocon.html"))
```

#### Fairness - all treatments

```{r 3051_fairness_all}

source("Functions/amce.R")

res_main <-  main_01 %>%
  amce(post_fair, treat_winningmargin, treat_winnergloat, treat_message, treat_messenger, treat_issue, treat_scale) 

res_main <- res_main %>% 
  mutate(
  treatment =  case_when(treatment == "treat_winningmargin" ~ "Winning\nmargin",
            treatment == "treat_winnergloat" ~ "Winner\ngloats",
            treatment == "treat_message" ~ "Democratic\nmessage",
            treatment == "treat_messenger" ~ "Messenger",
            treatment == "treat_issue" ~ "Issue",
            treatment == "treat_scale" ~ "Wording of answer scale")
)

#Figure
fig_amce <-
  res_main %>%
  ggplot(aes(x = estimate, y = value)) +
  facet_grid(
    treatment ~ .,
    scales = "free_y",
    space = "free_y") +
  geom_errorbarh(
    aes(xmin = estimate - (2 * std_error),
        xmax = estimate + (2 * std_error)),
    height = 0) +
  geom_point() +
  geom_vline(aes(xintercept = 0), linetype = "dotted") +
  scale_x_continuous(
    limits = c(-1, 1),
    breaks = round(seq(-1, 1, .1), 2),
    expand = c(0, 0)) +
    labs(
    x = "Marginal effect, fairness perception of decision",
    y = "",
    title = 'Average Marginal Component Effect -- Study 3') +
  theme_bw() +
  theme(plot.margin = unit(c(2, 2, 2, 2), "mm"),  plot.title = element_text(size=9), plot.subtitle = element_text(size=8), strip.text.y = element_text(size=6, angle=0) ,      axis.text.x=element_text(size=rel(0.7)))
fig_amce


ggsave("fig_losers_fair.png",
  plot = fig_amce,
  width = 6, height = 2.75
)


#table
res_main <- res_main %>% 
  select(value, estimate, std_error, statistic, p_value)


kable(res_main, booktabs = TRUE, caption = "Average Marginal Component Effect -- Study 3", col.names = linebreak(c("Treatment value", "Estimate", "Std. Error", "t-statistic", "p value")), digits = 2) %>% 
  kable_styling(bootstrap_options = c("striped", "hover", "responsive")) %>% 
 kableExtra::group_rows(index = c("Winning margin" = 3, "Winner gloating" = 2, "Good loser message" = 4, "Messenger" = 2, "Issue" = 2, "Wording of answer scale" = 2))

kable(res_main, booktabs = TRUE, caption = "Average Marginal Component Effect -- Study 3", col.names = linebreak(c("Treatment value", "Estimate", "Std. Error", "t-statistic", "p value")), digits = 2) %>% 
  kable_styling(bootstrap_options = c("striped", "hover", "responsive")) %>% 
  kableExtra::group_rows(index = c("Winning margin" = 3, "Winner gloating" = 2, "Good loser message" = 4, "Messenger" = 2, "Issue" = 2, "Wording of answer scale" = 2))%>% 
  cat(., file = here("output", "nocon", "tbls", "html",  "tbl-losers-fairness-nocon.html"))
```

#### Fairness - with covariates
```{r, 3052_fairness_covariates}
#AMCE with covariates

res_main <-  main_01 %>% mutate(polint = case_when(polint %in% 3:5 ~ 'Low political interest',
                                                   polint %in% 1:2 ~ 'High political interest')) %>% 
  amce(post_fair, treat_winningmargin, treat_winnergloat, treat_message, treat_messenger, treat_issue, treat_scale, gender, age, polint) 

res_main <- res_main %>% 
  mutate(
  value =  case_when(treatment == 'treat_winningmargin' & value == 'Not shown' ~ 'Not shown',
                     treatment == 'treat_winningmargin' & value == 'Slight majority' ~ 'Slight majority',
                     treatment == 'treat_winningmargin' & value == 'Large majority' ~ 'Large majority',
                     treatment == 'treat_winnergloat' & value == 'Not shown' ~ 'Not shown',
                     treatment == 'treat_winnergloat' & value == 'Winning politician gloats' ~ 'Winning politician gloats',
                     treatment == 'treat_message' & value == 'Not shown' ~ 'Not shown',
                     treatment == 'treat_message' & value == 'Lamenting politician' ~ 'Lamenting politician',
                     treatment == 'treat_message' & value == 'Specific good loser message' ~ 'Specific good loser message',
                     treatment == 'treat_message' & value == 'Generic good loser message' ~ 'Generic good loser message',
                     treatment == 'treat_message' & value == 'Lamenting politician' ~ 'Lamenting politician',
                     treatment == 'treat_messenger' & value == 'Local newspaper' ~ 'Local newspaper',
                     treatment == 'treat_messenger' & value == 'Political leader' ~ 'Political leader',
                     treatment == 'treat_issue' & value == 'Ban on begging' ~ 'Ban on begging',
                     treatment == 'treat_issue' & value == 'Road toll increase of diesel cars' ~ 'Road toll increase of diesel cars',
                     treatment == 'treat_scale' & value == 'Numbered' ~ 'Numbered',
                     treatment == 'treat_scale' & value == 'Worded' ~ 'Worded',
                     treatment == "gender" & value_order == '16' ~ "Male",
                     treatment == 'gender' & value_order == '17' ~ 'Female',
                     treatment == 'age' & value_order == '18' ~ 'Born before 1960',
                     treatment == 'age' & value_order == '19' ~ 'Born between 1960 and 1989',
                     treatment == 'age' & value_order == '20' ~ 'Born 1990 or later',
                     treatment == 'polint' & value_order == '21' ~ 'Low political interest',
                     treatment == 'polint' & value_order == '22' ~ 'High political interest')
  )


#table
res_main <- res_main %>% 
  select(value, estimate, std_error, statistic, p_value)

kable(res_main, booktabs = TRUE, caption = "Average Marginal Component Effect -- Study 3", col.names = linebreak(c("Treatments and covariates", "Estimate", "Std. Error", "t-statistic", "p value")), digits = 2) %>% 
  kable_styling(bootstrap_options = c("striped", "hover", "responsive")) %>% 
 kableExtra::group_rows(index = c("Winning margin" = 3, "Winner gloating" = 2, "Good loser message" = 4, "Messenger" = 2, "Issue" = 2, "Wording of answer scale" = 2, 'Gender' = 2, 'Age' = 3, 'Political interest' = 2))

kable(res_main, booktabs = TRUE, caption = "Average Marginal Component Effect -- Study 3", col.names = linebreak(c("Treatments and covariates", "Estimate", "Std. Error", "t-statistic", "p value")), digits = 2) %>% 
  kable_styling(bootstrap_options = c("striped", "hover", "responsive")) %>% 
  kableExtra::group_rows(index = c("Winning margin" = 3, "Winner gloating" = 2, "Good loser message" = 4, "Messenger" = 2, "Issue" = 2, "Wording of answer scale" = 2))%>% 
  kableExtra::group_rows(index = c("Winning margin" = 3, "Winner gloating" = 2, "Good loser message" = 4, "Messenger" = 2, "Issue" = 2, "Wording of answer scale" = 2, 'Gender' = 2, 'Age' = 3, 'Political interest' = 2)) %>% 
  cat(., file = here("output", "nocon", "tbls", "html",  "tbl-losers-fairness-nocon-covariate.html"))
```

#### Conditional AMCEs

> Outcome favorability: Includes both winners and losers.

```{r 3053_fairness_all}

source("Functions/amce.R")

res_main <-  main_00 %>%
  amce(post_fair, treat_winningmargin, treat_winnergloat, treat_message, treat_messenger, treat_issue, treat_scale, subgroup = 'treat_outfav') 
  
res_main <- res_main %>% 
  mutate(
  treatment =  case_when(treatment == "treat_winningmargin" ~ "Winning\nmargin",
            treatment == "treat_winnergloat" ~ "Winner\ngloats",
            treatment == "treat_message" ~ "Democratic\nmessage",
            treatment == "treat_messenger" ~ "Messenger",
            treatment == "treat_issue" ~ "Issue",
            treatment == "treat_scale" ~ "Wording of answer scale")
)

#Figure
fig_amce <-
  res_main %>%
  ggplot(aes(x = estimate, y = value)) +
  facet_grid(
    treatment ~ .,
    scales = "free_y",
    space = "free_y") +
  geom_errorbarh(
    aes(xmin = estimate - (2 * std_error),
        xmax = estimate + (2 * std_error)),
    height = 0) +
    geom_point(aes(colour = factor(treat_outfav))) +
  geom_vline(aes(xintercept = 0), linetype = "dotted") +
  scale_x_continuous(
    limits = c(-1, 1),
    breaks = round(seq(-1, 1, .1), 2),
    expand = c(0, 0)) +
    labs(
    x = "Marginal effect, fairness perception of decision",
    y = "",
    title = 'Average Marginal Component Effect -- Study 3',
    subtitle = 'Subgroups: Outcome favorability') +
  theme_bw() +
  theme(plot.margin = unit(c(2, 2, 2, 2), "mm"),  plot.title = element_text(size=9), plot.subtitle = element_text(size=8), strip.text.y = element_text(size=6, angle=0) ,      axis.text.x=element_text(size=rel(0.7)))
fig_amce



ggsave("fig_fair_outfav.png",
  plot = fig_amce,
  width = 6, height = 2.75
)

#table
res_main <- res_main %>% 
  select(value, estimate, std_error, statistic, p_value)


kable(res_main, booktabs = TRUE, caption = "Average Marginal Component Effect -- Study 3", col.names = linebreak(c("Treatment value", "Estimate", "Std. Error", "t-statistic", "p value")), digits = 2) %>% 
  kable_styling(bootstrap_options = c("striped", "hover", "responsive")) %>% 
  kableExtra::group_rows(index = c("Winning margin" = 3, "Winner gloating" = 2, "Good loser message" = 4, "Messenger" = 2, "Issue" = 2, "Wording of answer scale" = 2))%>% 
  cat(., file = here("output", "nocon", "tbls", "html",  "tbl-outfav-nocon.html"))
```

> Issue importance

```{r 3054_fairness_intimportance}

source("Functions/amce.R")

res_main <-  main_01 %>%
  amce(post_fair, treat_winningmargin, treat_winnergloat, treat_message, treat_messenger, treat_issue, treat_scale, subgroup = 'importance') 
  
res_main <- res_main %>% 
  mutate(
  treatment =  case_when(treatment == "treat_winningmargin" ~ "Winning\nmargin",
            treatment == "treat_winnergloat" ~ "Winner\ngloats",
            treatment == "treat_message" ~ "Democratic\nmessage",
            treatment == "treat_messenger" ~ "Messenger",
            treatment == "treat_issue" ~ "Issue",
            treatment == "treat_scale" ~ "Wording of answer scale")
)

#Figure
fig_amce <-
  res_main %>%
  ggplot(aes(x = estimate, y = value)) +
  facet_grid(
    treatment ~ .,
    scales = "free_y",
    space = "free_y") +
  geom_errorbarh(
    aes(xmin = estimate - (2 * std_error),
        xmax = estimate + (2 * std_error),
        colour = factor(importance)),
    height = 0) +
  geom_point(aes(colour = factor(importance))) +
  geom_vline(aes(xintercept = 0), linetype = "dotted") +
  scale_x_continuous(
    limits = c(-1, 1),
    breaks = round(seq(-1, 1, .2), 2),
    expand = c(0, 0)) +
    labs(
    x = "Marginal effect, fairness perception of decision",
    y = "",
    title = 'Average Marginal Component Effect -- Study 3',
    subtitle = 'Subgroups: Issue importance.') +
  theme_bw() +
  theme(plot.margin = unit(c(2, 2, 2, 2), "mm"),  plot.title = element_text(size=9), plot.subtitle = element_text(size=8), strip.text.y = element_text(size=6, angle=0) ,      axis.text.x=element_text(size=rel(0.7)))
fig_amce


ggsave("fig_losers_fair_importance.png",
  plot = fig_amce,
  width = 6, height = 2.75
)

#table
res_main <- res_main %>% 
  select(value, estimate, std_error, statistic, p_value, importance)


kable(res_main, booktabs = TRUE, caption = "Average Marginal Component Effect -- Study 3", col.names = linebreak(c("Treatment value", "Estimate", "Std. Error", "t-statistic", "p value", "Issue importance")), digits = 2) %>% 
  kable_styling(bootstrap_options = c("striped", "hover", "responsive")) %>% 
 kableExtra::group_rows(index = c("Winning margin" = 6, "Winner gloating" = 4, "Good loser message" = 8, "Messenger" = 4, "Issue" = 4, "Wording of answer scale" = 4))%>% 
  cat(., file = here("output", "nocon", "tbls", "html",  "tbl-losers-fairness-importance-nocon.html"))
```

Issue (ban on begging or road toll)
```{r 3055_fairness_issue}

source("Functions/amce.R")

res_main <-  main_01 %>%
  amce(post_fair, treat_winningmargin, treat_winnergloat, treat_message, treat_messenger, treat_issue,treat_scale, subgroup = 'treat_issue') 
  
res_main <- res_main %>% 
  mutate(
  treatment =  case_when(treatment == "treat_winningmargin" ~ "Winning\nmargin",
            treatment == "treat_winnergloat" ~ "Winner\ngloats",
            treatment == "treat_message" ~ "Democratic\nmessage",
            treatment == "treat_messenger" ~ "Messenger",
            treatment == "treat_issue" ~ "Issue",
            treatment == "treat_scale" ~ "Wording of answer scale")
)

#Figure
fig_amce <-
  res_main %>%
  ggplot(aes(x = estimate, y = value)) +
  facet_grid(
    treatment ~ .,
    scales = "free_y",
    space = "free_y") +
   geom_errorbarh(
    aes(xmin = estimate - (2 * std_error),
        xmax = estimate + (2 * std_error),
        colour = factor(treat_issue)),
    height = 0) +
  geom_point(aes(colour = factor(treat_issue))) +
  geom_vline(aes(xintercept = 0), linetype = "dotted") +
  scale_x_continuous(
    limits = c(-1, 1),
    breaks = round(seq(-1, 1, .2), 2),
    expand = c(0, 0)) +
    labs(
    x = "Marginal effect, fairness perception of decision",
    y = "",
    title = 'Average Marginal Component Effect -- Study 3') +
  theme_bw() +
  theme(plot.margin = unit(c(2, 2, 2, 2), "mm"),  plot.title = element_text(size=9), plot.subtitle = element_text(size=8), strip.text.y = element_text(size=6, angle=0) ,      axis.text.x=element_text(size=rel(0.7)))
fig_amce


ggsave("fig_losers_intissue_fair.png",
  plot = fig_amce,
  width = 6, height = 2.75
)

#table
res_main <- res_main %>% 
  select(value, estimate, std_error, statistic, p_value)

kable(res_main, booktabs = TRUE, caption = "Average Marginal Component Effect -- Study 3", col.names = linebreak(c("Treatment value", "Estimate", "Std. Error", "t-statistic", "p value")), digits = 2) %>% 
  kable_styling(bootstrap_options = c("striped", "hover", "responsive")) %>% 
  kableExtra::group_rows(index = c("Winning margin" = 3, "Winner gloating" = 2, "Good loser message" = 4, "Messenger" = 2, "Issue" = 2, "Wording of answer scale" = 2))%>% 
  cat(., file = here("output", "nocon", "tbls", "html",  "tbl-losers-fairness-intissue-nocon.html"))
```

### Acceptance
```{r 3056_accept}

source("Functions/amce.R")

res_main <-  main_01 %>%
  amce(post_accept, treat_winningmargin, treat_winnergloat, treat_message, treat_messenger, treat_issue, treat_scale) 
  
res_main <- res_main %>% 
  mutate(
  treatment =  case_when(treatment == "treat_winningmargin" ~ "Winning\nmargin",
            treatment == "treat_winnergloat" ~ "Winner\ngloats",
            treatment == "treat_message" ~ "Democratic\nmessage",
            treatment == "treat_messenger" ~ "Messenger",
            treatment == "treat_issue" ~ "Issue",
            treatment == "treat_scale" ~ "Wording of answer scale")
)

#Figure
fig_amce <-
  res_main %>%
  ggplot(aes(x = estimate, y = value)) +
  facet_grid(
    treatment ~ .,
    scales = "free_y",
    space = "free_y") +
  geom_errorbarh(
    aes(xmin = estimate - (2 * std_error),
        xmax = estimate + (2 * std_error)),
    height = 0) +
  geom_point() +
  geom_vline(aes(xintercept = 0), linetype = "dotted") +
  scale_x_continuous(
    limits = c(-1, 1),
    breaks = round(seq(-1, 1, .2), 2),
    expand = c(0, 0)) +
   labs(
    x = "Marginal effect, willingnes to accept decision",
    y = "",
    title = 'Average Marginal Component Effect -- Study 3') +
  theme_bw() +
  theme(plot.margin = unit(c(2, 2, 2, 2), "mm"),  plot.title = element_text(size=9), plot.subtitle = element_text(size=8), strip.text.y = element_text(size=6, angle=0) ,      axis.text.x=element_text(size=rel(0.7)))
fig_amce

ggsave("fig_losers_accept.png",
  plot = fig_amce,
  width = 6, height = 2.75
)

#table
res_main <- res_main %>% 
  select(value, estimate, std_error, statistic, p_value)


kable(res_main, booktabs = TRUE, caption = "Average Marginal Component Effects -- Study 3", col.names = linebreak(c("Treatment value", "Estimate", "Std. Error", "t-statistic", "p value")), digits = 2) %>%
  kable_styling(bootstrap_options = c("striped", "hover", "responsive")) %>% 
 kableExtra::group_rows(index = c("Winning margin" = 3, "Winner gloating" = 2, "Good loser message" = 4, "Messenger" = 2, "Issue" = 2, "Wording of answer scale" = 2))

kable(res_main, booktabs = TRUE, caption = "Average Marginal Component Effects -- Study 3", col.names = linebreak(c("Treatment value", "Estimate", "Std. Error", "t-statistic", "p value")), digits = 2) %>%
  kable_styling(bootstrap_options = c("striped", "hover", "responsive")) %>% 
 kableExtra::group_rows(index = c("Winning margin" = 3, "Winner gloating" = 2, "Good loser message" = 4, "Messenger" = 2, "issue" = 2, "Wording of answer scale" = 2))%>% 
  cat(., file = here("output", "nocon", "tbls", "html",  "tbl-losers-accept-nocon.html"))

```

#### Acceptance - with covariates
```{r, 3057_accept_covariates}
#AMCE with covariates

res_main <-  main_01 %>% mutate(polint = case_when(polint %in% 3:5 ~ 'Low political interest',
                                                   polint %in% 1:2 ~ 'High political interest')) %>% 
  amce(post_accept, treat_winningmargin, treat_winnergloat, treat_message, treat_messenger, treat_issue, treat_scale, gender, age, polint) 

res_main <- res_main %>% 
  mutate(
  value =  case_when(treatment == 'treat_winningmargin' & value == 'Not shown' ~ 'Not shown',
                     treatment == 'treat_winningmargin' & value == 'Slight majority' ~ 'Slight majority',
                     treatment == 'treat_winningmargin' & value == 'Large majority' ~ 'Large majority',
                     treatment == 'treat_winnergloat' & value == 'Not shown' ~ 'Not shown',
                     treatment == 'treat_winnergloat' & value == 'Winning politician gloats' ~ 'Winning politician gloats',
                     treatment == 'treat_message' & value == 'Not shown' ~ 'Not shown',
                     treatment == 'treat_message' & value == 'Lamenting politician' ~ 'Lamenting politician',
                     treatment == 'treat_message' & value == 'Specific good loser message' ~ 'Specific good loser message',
                     treatment == 'treat_message' & value == 'Generic good loser message' ~ 'Generic good loser message',
                     treatment == 'treat_message' & value == 'Lamenting politician' ~ 'Lamenting politician',
                     treatment == 'treat_messenger' & value == 'Local newspaper' ~ 'Local newspaper',
                     treatment == 'treat_messenger' & value == 'Political leader' ~ 'Political leader',
                     treatment == 'treat_issue' & value == 'Ban on begging' ~ 'Ban on begging',
                     treatment == 'treat_issue' & value == 'Road toll increase of diesel cars' ~ 'Road toll increase of diesel cars',
                     treatment == 'treat_scale' & value == 'Numbered' ~ 'Numbered',
                     treatment == 'treat_scale' & value == 'Worded' ~ 'Worded',
                     treatment == "gender" & value_order == '16' ~ "Male",
                     treatment == 'gender' & value_order == '17' ~ 'Female',
                     treatment == 'age' & value_order == '18' ~ 'Born before 1960',
                     treatment == 'age' & value_order == '19' ~ 'Born between 1960 and 1989',
                     treatment == 'age' & value_order == '20' ~ 'Born 1990 or later',
                     treatment == 'polint' & value_order == '21' ~ 'Low political interest',
                     treatment == 'polint' & value_order == '22' ~ 'High political interest')
  )


#table
res_main <- res_main %>% 
  select(value, estimate, std_error, statistic, p_value)

kable(res_main, booktabs = TRUE, caption = "Average Marginal Component Effect -- Study 3", col.names = linebreak(c("Treatments and covariates", "Estimate", "Std. Error", "t-statistic", "p value")), digits = 2) %>% 
  kable_styling(bootstrap_options = c("striped", "hover", "responsive")) %>% 
 kableExtra::group_rows(index = c("Winning margin" = 3, "Winner gloating" = 2, "Good loser message" = 4, "Messenger" = 2, "Issue" = 2, "Wording of answer scale" = 2, 'Gender' = 2, 'Age' = 3, 'Political interest' = 2))

#save to file
kable(res_main, booktabs = TRUE, caption = "Average Marginal Component Effect -- Study 3", col.names = linebreak(c("Treatments and covariates", "Estimate", "Std. Error", "t-statistic", "p value")), digits = 2) %>% 
  kable_styling(bootstrap_options = c("striped", "hover", "responsive")) %>% 
  kableExtra::group_rows(index = c("Winning margin" = 3, "Winner gloating" = 2, "Good loser message" = 4, "Messenger" = 2, "Issue" = 2, "Wording of answer scale" = 2))%>% 
  kableExtra::group_rows(index = c("Winning margin" = 3, "Winner gloating" = 2, "Good loser message" = 4, "Messenger" = 2, "Issue" = 2, "Wording of answer scale" = 2, 'Gender' = 2, 'Age' = 3, 'Political interest' = 2)) %>% 
  cat(., file = here("output", "nocon", "tbls", "html",  "tbl-losers-accept-nocon-covariate.html"))
```
### Reasonable decision
```{r 3058_reasonable}

source("Functions/amce.R")

res_main <-  main_01 %>%
  amce(post_reasonable, treat_winningmargin, treat_winnergloat, treat_message, treat_messenger, treat_issue, treat_scale) 
  
res_main <- res_main %>% 
  mutate(
  treatment =  case_when(treatment == "treat_winningmargin" ~ "Winning\nmargin",
            treatment == "treat_winnergloat" ~ "Winner\ngloats",
            treatment == "treat_message" ~ "Democratic\nmessage",
            treatment == "treat_messenger" ~ "Messenger",
            treatment == "treat_issue" ~ "Issue",
            treatment == "treat_scale" ~ "Wording of answer scale")
)

#Figure
fig_amce <-
  res_main %>%
  ggplot(aes(x = estimate, y = value)) +
  facet_grid(
    treatment ~ .,
    scales = "free_y",
    space = "free_y") +
  geom_errorbarh(
    aes(xmin = estimate - (2 * std_error),
        xmax = estimate + (2 * std_error)),
    height = 0) +
  geom_point() +
  geom_vline(aes(xintercept = 0), linetype = "dotted") +
  scale_x_continuous(
    limits = c(-1, 1),
    breaks = round(seq(-1, 1, .2), 2),
    expand = c(0, 0)) +
   labs(
    x = "Marginal effect, reasonable decision",
    y = "",
    title = 'Average Marginal Component Effect -- Study 3') +
  theme_bw() +
  theme(plot.margin = unit(c(2, 2, 2, 2), "mm"),  plot.title = element_text(size=9), plot.subtitle = element_text(size=8), strip.text.y = element_text(size=6, angle=0) ,      axis.text.x=element_text(size=rel(0.7)))
fig_amce

ggsave("fig_losers_accept.png",
  plot = fig_amce,
  width = 6, height = 2.75
)

#table
res_main <- res_main %>% 
  select(value, estimate, std_error, statistic, p_value)


kable(res_main, booktabs = TRUE, caption = "Average Marginal Component Effects -- Study 3", col.names = linebreak(c("Treatment value", "Estimate", "Std. Error", "t-statistic", "p value")), digits = 2) %>%
  kable_styling(bootstrap_options = c("striped", "hover", "responsive")) %>% 
 kableExtra::group_rows(index = c("Winning margin" = 3, "Winner gloating" = 2, "Good loser message" = 4, "Messenger" = 2, "Issue" = 2, "Wording of answer scale" = 2))

kable(res_main, booktabs = TRUE, caption = "Average Marginal Component Effects -- Study 3", col.names = linebreak(c("Treatment value", "Estimate", "Std. Error", "t-statistic", "p value")), digits = 2) %>%
  kable_styling(bootstrap_options = c("striped", "hover", "responsive")) %>% 
 kableExtra::group_rows(index = c("Winning margin" = 3, "Winner gloating" = 2, "Good loser message" = 4, "Messenger" = 2, "issue" = 2, "Wording of answer scale" = 2))%>% 
  cat(., file = here("output", "nocon", "tbls", "html",  "tbl-losers-reasonable-nocon.html"))
```

#### Reasonable decision - with covariates

```{r, 3059_reasonable_covariates}
#AMCE with covariates

res_main <-  main_01 %>% mutate(polint = case_when(polint %in% 3:5 ~ 'Low political interest',
                                                   polint %in% 1:2 ~ 'High political interest')) %>% 
  amce(post_reasonable, treat_winningmargin, treat_winnergloat, treat_message, treat_messenger, treat_issue, treat_scale, gender, age, polint) 

res_main <- res_main %>% 
  mutate(
  value =  case_when(treatment == 'treat_winningmargin' & value == 'Not shown' ~ 'Not shown',
                     treatment == 'treat_winningmargin' & value == 'Slight majority' ~ 'Slight majority',
                     treatment == 'treat_winningmargin' & value == 'Large majority' ~ 'Large majority',
                     treatment == 'treat_winnergloat' & value == 'Not shown' ~ 'Not shown',
                     treatment == 'treat_winnergloat' & value == 'Winning politician gloats' ~ 'Winning politician gloats',
                     treatment == 'treat_message' & value == 'Not shown' ~ 'Not shown',
                     treatment == 'treat_message' & value == 'Lamenting politician' ~ 'Lamenting politician',
                     treatment == 'treat_message' & value == 'Specific good loser message' ~ 'Specific good loser message',
                     treatment == 'treat_message' & value == 'Generic good loser message' ~ 'Generic good loser message',
                     treatment == 'treat_message' & value == 'Lamenting politician' ~ 'Lamenting politician',
                     treatment == 'treat_messenger' & value == 'Local newspaper' ~ 'Local newspaper',
                     treatment == 'treat_messenger' & value == 'Political leader' ~ 'Political leader',
                     treatment == 'treat_issue' & value == 'Ban on begging' ~ 'Ban on begging',
                     treatment == 'treat_issue' & value == 'Road toll increase of diesel cars' ~ 'Road toll increase of diesel cars',
                     treatment == 'treat_scale' & value == 'Numbered' ~ 'Numbered',
                     treatment == 'treat_scale' & value == 'Worded' ~ 'Worded',
                     treatment == "gender" & value_order == '16' ~ "Male",
                     treatment == 'gender' & value_order == '17' ~ 'Female',
                     treatment == 'age' & value_order == '18' ~ 'Born before 1960',
                     treatment == 'age' & value_order == '19' ~ 'Born between 1960 and 1989',
                     treatment == 'age' & value_order == '20' ~ 'Born 1990 or later',
                     treatment == 'polint' & value_order == '21' ~ 'Low political interest',
                     treatment == 'polint' & value_order == '22' ~ 'High political interest')
  )


#table
res_main <- res_main %>% 
  select(value, estimate, std_error, statistic, p_value)

kable(res_main, booktabs = TRUE, caption = "Average Marginal Component Effect -- Study 3", col.names = linebreak(c("Treatments and covariates", "Estimate", "Std. Error", "t-statistic", "p value")), digits = 2) %>% 
  kable_styling(bootstrap_options = c("striped", "hover", "responsive")) %>% 
 kableExtra::group_rows(index = c("Winning margin" = 3, "Winner gloating" = 2, "Good loser message" = 4, "Messenger" = 2, "Issue" = 2, "Wording of answer scale" = 2, 'Gender' = 2, 'Age' = 3, 'Political interest' = 2))

#save to file
kable(res_main, booktabs = TRUE, caption = "Average Marginal Component Effect -- Study 3", col.names = linebreak(c("Treatments and covariates", "Estimate", "Std. Error", "t-statistic", "p value")), digits = 2) %>% 
  kable_styling(bootstrap_options = c("striped", "hover", "responsive")) %>% 
  kableExtra::group_rows(index = c("Winning margin" = 3, "Winner gloating" = 2, "Good loser message" = 4, "Messenger" = 2, "Issue" = 2, "Wording of answer scale" = 2))%>% 
  kableExtra::group_rows(index = c("Winning margin" = 3, "Winner gloating" = 2, "Good loser message" = 4, "Messenger" = 2, "Issue" = 2, "Wording of answer scale" = 2, 'Gender' = 2, 'Age' = 3, 'Political interest' = 2)) %>% 
  cat(., file = here("output", "nocon", "tbls", "html",  "tbl-losers-reasonable-nocon-covariate.html"))
```
\newpage
## Differential attrition check

```{r, 3060_attrition}
d <- import(here("Data", "Goodloser-exp3.rds"))
d <- d %>% mutate(treat_outcome = case_when(outcome == 1 ~ "The Yes side won the vote",
                                 outcome == 2 ~ "The No side won the vote"),
                  treat_outfav = case_when(issue == 1 & opinion_begging == 1 & outcome == 1 ~ "Favorable outcome",
                                  issue == 1 & opinion_begging == 2 & outcome == 2 ~ "Favorable outcome",
                                  issue == 1 & opinion_begging == 1 & outcome == 2 ~ "Unfavorable outcome",
                                  issue == 1 & opinion_begging == 2 & outcome == 1 ~ "Unfavorable outcome",
                                  issue == 2 & opinion_toll == 1 & outcome == 1 ~ "Favorable outcome",
                                  issue == 2 & opinion_toll == 2 & outcome == 2 ~ "Favorable outcome",
                                  issue == 2 & opinion_toll == 1 & outcome == 2 ~ "Unfavorable outcome",
                                  issue == 2 & opinion_toll == 2 & outcome == 1 ~ "Unfavorable outcome"),
                  treat_issue = case_when(issue == 1 ~ "Ban on begging",
                                          issue == 2 ~ "Road toll increase of diesel cars"),
                  treat_winningmargin = case_when(margin == 1 ~ "Not shown",
                                                  margin == 2 ~ "Slight majority",
                                                  margin == 3 ~ "Large majority"),
                  treat_winnergloat = case_when(winner == 1 ~ "Not shown",
                                                winner == 2 ~ "Winning politician gloats"),
                  treat_message = case_when(messenger == 1 ~ "Not shown",
                                            messenger == 2  | messenger == 5 ~ "Lamenting politician",
                                            messenger == 3  | messenger == 6 ~ "Specific good loser message",
                                            messenger == 4 | messenger == 7 ~ "Generic good loser message"),
                  treat_messenger = case_when(messenger %in% 3:4 ~ "Political leader",
                                              messenger %in% 6:7 ~ "Local newspaper"),
                  treat_scale = case_when(r13pad6_ran == 1 ~ "Worded",
                                          r13pad6_ran == 2 ~ "Numbered"),
                  post_fair = case_when(fairness_a == 1 | fairness_b == 1 ~ 5, #Reverse scales
                                        fairness_a == 2 | fairness_b == 2 ~ 4,
                                        fairness_a == 3 | fairness_b == 3 ~ 3,
                                        fairness_a == 4 | fairness_b == 4 ~ 2,
                                        fairness_a == 5 | fairness_b == 5 ~ 1),
                  post_accept = case_when(accept_a == 1 | accept_b == 1 ~ 5,
                                          accept_a == 2 | accept_b == 2 ~ 4,
                                          accept_a == 3 | accept_b == 3 ~ 3,
                                          accept_a == 4 | accept_b == 4 ~ 2,
                                          accept_a == 5 | accept_b == 5 ~ 1)

  ) %>% 

 # replace_with_na_all(condition = ~.x == 98 )%>%  #Recode 98 (not asked) as missing
  filter(!is.na(r13pad6_ran)) %>%  #Remove respondents who did not receive the post measures
## We want the value labels in particular order for the tables and figures.
        mutate(treat_winningmargin = lvls_reorder(treat_winningmargin, c(2, 3, 1)), 
               treat_message = lvls_reorder(treat_message, c(3, 2, 4, 1)) 
        ) %>%
  mutate(attr_fairness = case_when(is.na(post_fair) ~ 1,
                                                    TRUE ~ 0),
                          attr_accept = case_when(is.na(post_accept) ~ 1,
                                                  TRUE ~ 0))
#Fairness
res_main <- lm_robust(attr_fairness ~ treat_message + treat_issue + treat_winningmargin + treat_winnergloat + treat_scale, data = d)
res_main <- tidy(res_main)

table <- res_main %>%
  select(term, estimate, std.error, statistic, p.value) %>%
  filter(term != '(Intercept)') %>% 
  mutate(term = case_when( term == "treat_messageLamenting politician" ~ "Lamenting politician",
                   term == "treat_messageGeneric good loser message" ~ "Generic good loser message",
                   term == "treat_messageSpecific good loser message" ~ "Specific good loser message",
                   term == 'treat_issueRoad toll increase of diesel cars' ~ 'Road toll increase of diesel cars',
                   term == 'treat_winningmarginSlight majority' ~ 'Slight majority',
                   term == 'treat_winningmarginLarge majority' ~ 'Large majority',
                   term == 'treat_winnergloatWinning politician gloats' ~ 'Winning politician gloats',
                   term == 'treat_scaleWorded' ~ 'Worded response scale'))

kable(table, booktabs = TRUE, caption = "Differential attrition across treatment conditions, Study 2. Fairness.", col.names = linebreak(c("Treatment value", "Estimate", "Std. Error", "t-statistic", "p value")), digits = 2) %>%
  kable_styling(bootstrap_options = c("striped", "hover", "responsive")) %>% 
  kableExtra::group_rows(index = c("Good loser message" = 3, "Issue" = 1, "Winning margin" = 2, "Winner gloating" = 1, "Wording of answer scale" = 1)) %>% 
  footnote(general = 'Reference category for Good loser message is *Not shown*; for Issue *Ban on begging*; for Winning margin *Not shown*; for Winner gloating *Not shown*; and for Wording of response scale *Numbered*. F-statistic: 1.72 on 8 and 2810 DF,  p-value: 0.088')

#save to file
kable(table, booktabs = TRUE, caption = "Differential attrition across treatment conditions, Study 2, Fairness.", col.names = linebreak(c("Treatment value", "Estimate", "Std. Error", "t-statistic", "p value")), digits = 2) %>%
  kable_styling(bootstrap_options = c("striped", "hover", "responsive"))  %>%
  kableExtra::group_rows(index = c("Good loser message" = 3, "Issue" = 1, "Winning margin" = 2, "Winner gloating" = 1, "Wording of answer scale" = 1)) %>% 
  footnote(general = 'Reference category for Good loser message is *Not shown*; for Issue *Ban on begging*; for Winning margin *Not shown*; for Winner gloating *Not shown*; and for Wording of response scale *Numbered*. F-statistic: 1.72 on 8 and 2810 DF,  p-value: 0.088') %>% 
  cat(., file = here("output", "novig", "tbls", "html",  "tbl-attrition-fairness-nocon.html"))

#Willingness to accept
res_main <- lm_robust(attr_accept ~ treat_message + treat_issue + treat_winningmargin + treat_winnergloat + treat_scale, data = d)
res_main <- tidy(res_main)

table <- res_main %>%
  select(term, estimate, std.error, statistic, p.value) %>%
  filter(term != '(Intercept)') %>% 
  mutate(term = case_when( term == "treat_messageLamenting politician" ~ "Lamenting politician",
                   term == "treat_messageGeneric good loser message" ~ "Generic good loser message",
                   term == "treat_messageSpecific good loser message" ~ "Specific good loser message",
                   term == 'treat_issueRoad toll increase of diesel cars' ~ 'Road toll increase of diesel cars',
                   term == 'treat_winningmarginSlight majority' ~ 'Slight majority',
                   term == 'treat_winningmarginLarge majority' ~ 'Large majority',
                   term == 'treat_winnergloatWinning politician gloats' ~ 'Winning politician gloats',
                   term == 'treat_scaleWorded' ~ 'Worded response scale'))

kable(table, booktabs = TRUE, caption = "Differential attrition across treatment conditions, Study 2.  Willingess to accept.", col.names = linebreak(c("Treatment value", "Estimate", "Std. Error", "t-statistic", "p value")), digits = 2) %>%
  kable_styling(bootstrap_options = c("striped", "hover", "responsive")) %>% 
  kableExtra::group_rows(index = c("Good loser message" = 3, "Issue" = 1, "Winning margin" = 2, "Winner gloating" = 1, "Wording of answer scale" = 1)) %>% 
  footnote(general = 'Reference category for Good loser message is *Not shown*; for Issue *Ban on begging*; for Winning margin *Not shown*; for Winner gloating *Not shown*; and for Wording of response scale *Numbered*. F-statistic: 1.13 on 8 and 2810 DF,  p-value: 0.34')

#save to file
kable(table, booktabs = TRUE, caption = "Differential attrition across treatment conditions, Study 2. Willingess to accept", col.names = linebreak(c("Treatment value", "Estimate", "Std. Error", "t-statistic", "p value")), digits = 2) %>%
  kable_styling(bootstrap_options = c("striped", "hover", "responsive"))  %>%
  kableExtra::group_rows(index = c("Good loser message" = 3, "Issue" = 1, "Winning margin" = 2, "Winner gloating" = 1, "Wording of answer scale" = 1)) %>% 
  footnote(general = 'Reference category for Good loser message is *Not shown*; for Issue *Ban on begging*; for Winning margin *Not shown*; for Winner gloating *Not shown*; and for Wording of response scale *Numbered*. F-statistic: 1.13 on 8 and 2810 DF,  p-value: 0.34') %>% 
  cat(., file = here("output", "novig", "tbls", "html",  "tbl-attrition-accept-nocon.html"))
```


\newpage
# STUDY I-III
## Outcome favorability effect across the three experiments

```{r 4010_import, include=FALSE}
d1 <- import(here("Data", 'Goodloser-exp1.rds'))
d2 <- import(here("Data", "Goodloser-exp2.rds"))
d3 <- main_00
```

### Fairness - Outcome favorability

> Figure 1 in the manuscript:

```{r 4020_outfav_fair}

p1 <- d1 %>% mutate(favorability = case_when(favorability == 'Unfavorable' ~ 'Unfavorable outcome',
                                             favorability == 'Favorable' ~ 'Favorable outcome')) %>% 
  ggplot(aes(x = favorability, y = fairness)) +
  stat_summary(fun.data = mean_cl_normal, geom = 'point') +
  stat_summary(fun.data = mean_cl_normal, geom = 'linerange') +
  scale_y_continuous(limits = c(1, 7),
                     breaks = 1:7, 
                     labels = c('1 Not fair at all', '2', '3', '4', '5', '6', '7 Very fair')) +
  labs(x = " ",
       y = "",
       title = 'Study 1') +
  theme_bw() +
  coord_flip()

p2 <- d2 %>% mutate(favorability = case_when(favorability == 'Unfavorable' ~ 'Unfavorable outcome',
                                             favorability == 'Favorable' ~ 'Favorable outcome')) %>% 
  ggplot(aes(x = favorability, y = fairness)) +
  stat_summary(fun.data = mean_cl_normal, geom = 'point') +
  stat_summary(fun.data = mean_cl_normal, geom = 'linerange') +
  scale_y_continuous(limits = c(1, 5),
                     breaks = 1:5, 
                     labels = c('1 Not fair at all', '2', '3', '4', '5 Very fair')) +
  labs(x = " ",
       y = "", 
       title = 'Study 2') +
  theme_bw() +
  coord_flip()

p3 <- d3 %>% filter(!is.na(treat_outfav)) %>% 
  ggplot(aes(x = treat_outfav, y = post_fair)) +
  stat_summary(fun.data = mean_cl_normal, geom = 'point') +
  stat_summary(fun.data = mean_cl_normal, geom = 'linerange') +
  scale_y_continuous(limits = c(1, 5),
                     breaks = 1:5, 
                     labels = c('1 Not fair at all', '2', '3', '4', '5 Very fair')) +
  labs(x = " ",
       y = "", 
       title = 'Study 3') +
  theme_bw() +
  coord_flip()

patchwork <- p1 / p2 / p3
patchwork + plot_annotation(title = 'Fairness perceptions among winners and losers', 
                            subtitle = 'Results across three separate studies of political decision scenarios')

 ggsave(
   here("figure1-outfav-fair.png"),
   plot = patchwork,
   width = 5.5, height = 4.75, dpi = 600
 )
 
#table
res_main_01 <-  lm(fairness ~ favorability, data = d1)
res_main_01 <- broom::tidy(res_main_01) %>%
  mutate(value = case_when(term=='favorabilityUnfavorable' ~ 'Unfavorable outcome'),
         treatment = 'Study 1')%>%
  rename(std_error = std.error,
         p_value = p.value)

res_main_02 <-  lm(fairness ~ favorability, data = d2)
res_main_02 <- broom::tidy(res_main_02)%>%
  mutate(value = case_when(term=='favorabilityUnfavorable' ~ 'Unfavorable outcome'),
         treatment = 'Study 2') %>%
  rename(std_error = std.error,
         p_value = p.value)

source("Functions/amce.R")

res_main_03 <-  d3 %>%
  amce(post_fair, treat_outfav)  %>%
  mutate(treatment =  case_when(treatment == "treat_outfav" ~ "Study 3"))

res_main <- bind_rows(res_main_01, res_main_02)
res_main <- bind_rows(res_main, res_main_03)

res_main <- res_main %>%
  filter(value=='Unfavorable outcome') %>%
  select(treatment, estimate, std_error, statistic, p_value)

kable(res_main, booktabs = TRUE, caption = "The outcome favorability effect in three experiments", col.names = linebreak(c("Treatment value", "Estimate", "Std. Error", "t-statistic", "p value")), digits = 2) %>%
  kable_styling(bootstrap_options = c("striped", "hover", "responsive"))
#save to file
kable(res_main, booktabs = TRUE, caption = "The outcome favorability effect in three experiments", col.names = linebreak(c("Treatment value", "Estimate", "Std. Error", "t-statistic", "p value")), digits = 2) %>%
  kable_styling(bootstrap_options = c("striped", "hover", "responsive")) %>%
  cat(., file = here("output", "nocon", "tbls", "html",  "tbl-outfav-fair-all.html"))


```

### Outcome favorability by issue, Study 3
```{r 4021_outfav_issue}
res_main <-  d3 %>%
  amce(post_fair, treat_outfav, subgroup = 'treat_issue') 

res_main <- res_main %>%
  filter(value=='Unfavorable outcome') %>% 
  select(treatment, estimate, std_error, statistic, value, p_value, treat_issue)

res_main <- res_main %>% select(-value) %>% 
  mutate(treatment = case_when(treatment=='treat_outfav' ~ 'Unfavorable outcome'))

kable(res_main, booktabs = TRUE, caption = "The outcome favorability effect by issue, Experiment 3", col.names = linebreak(c("Treatment value", "Estimate", "Std. Error", "t-statistic", "p value", "Issue")), digits = 2) %>%
  kable_styling(bootstrap_options = c("striped", "hover", "responsive")) 
#save to file
kable(res_main, booktabs = TRUE, caption = "The outcome favorability effect by issue, Experiment 3", col.names = linebreak(c("Treatment value", "Estimate", "Std. Error", "t-statistic", "p value", "Issue")), digits = 2) %>%
  kable_styling(bootstrap_options = c("striped", "hover", "responsive")) %>% 
  cat(., file = here("output", "nocon", "tbls", "html",  "tbl-outfav-fair-study3-issue.html"))

```
\newpage

# Session Info R packages

```{r}
sessionInfo()
```

\newpage
# References